Error while trying to put items from database in access into combobox (visual basic)


  • Hello,

    I'm trying to fill a combobox with items from my database that I made in access.

    I always get the same error when I try to run it: System.NullReferenceException: Object reference not set to an instance of an object.

    Here is the part of code where I get the error. It's the function vulComboType:

    Imports System.Data
    Imports System.Data.OleDb
    Public Class EetdagDB
        Private connectiestring As String = My.Settings.EetdagConnectionString
        Private connectie As OleDbConnection
        Public Sub New()
            connectie = New OleDbConnection(connectiestring)
        End Sub
        Public Function vulComboType(box As ComboBox) As ComboBox
            box.Items.Add(" ")
            Dim query As String
            query = "SELECT Type FROM Items"
            Dim command As OleDbCommand
            command = New OleDbCommand(query, connectie)
            Dim Datareader As OleDbDataReader
            Datareader = command.ExecuteReader()
            While Datareader.Read
                Dim item As New ComboBoxItem
                item.Content = Datareader("Type")
            End While
            Return box
        End Function
    End Class

    Hope someone could help.

    Kind Regards


    Wednesday, April 12, 2017 1:59 PM

All replies

  • Hi Samekemas,

    According to your description, you want to fill comboBox with data from Access. You need to get data from Access and put into the DataTable dt, then bind dt to the ComboBox DataSource.

    Please refer to the code sample below.

    Imports System.Data.OleDb
    Public Class ComboxControl
        Private Sub ComboxControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        End Sub
        Private Sub loaddate()
            Dim dt As New DataTable
            Dim constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Database\ComBoxControl.accdb; Persist Security Info=False;"
            Dim conn = New OleDbConnection(constr)
            Dim selectSql = "select ID, CustomerName from Test1 "
            Dim com As New OleDbCommand(selectSql, conn)
            Dim adapter As New OleDbDataAdapter(com)
            ComboBox1.DataSource = dt
            ComboBox1.DisplayMember = "CustomerName"
            ComboBox1.ValueMember = "ID"
        End Sub
    End Class

    Hope it is helpful to you.

    Best Regards,

    Cherry Bu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, April 25, 2017 6:22 AM