1

I have the following code to bind the combobox from the database table:

Public Sub FillComboBox(ByVal cboCombo As ComboBox, ByVal sSQL As String, ByVal strTable As String, ByVal strDisplayMember As String, ByVal strValueMember As String)
    Dim CN As New OleDbConnection

    Try
        With CN
            If .State = ConnectionState.Open Then .Close()

            .ConnectionString = cnString
            .Open()
        End With

        Dim da As OleDbDataAdapter = New OleDbDataAdapter(sSQL, CN)
        Dim dt As New DataSet

        da.Fill(dt, strTable)

        cboCombo.DataSource = dt.Tables(strTable).DefaultView
        cboCombo.DisplayMember = strDisplayMember
        cboCombo.ValueMember = strValueMember
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        Debug.Print(ex.Message)
    Finally
        CN.Close()
    End Try
End Sub

Since "Select Item" value is not part of the record from the table, how can I add it in the combobox?

jaypabs
  • 1,519
  • 10
  • 43
  • 62

2 Answers2

3

I think you can add an additional Datarow from it, something like this.

    Dim da As OleDbDataAdapter = New OleDbDataAdapter(sSQL, CN)
    Dim dt As New DataSet

    da.Fill(dt, strTable)

    cboCombo.DataSource = dt.Tables(strTable).DefaultView
    cboCombo.DisplayMember = strDisplayMember
    cboCombo.ValueMember = strValueMember


    Dim dr As DataRow = dt.Tables(strTable).NewRow()
       dr(0) = "-1"
       dr(1) = "Select Item"
       dt.Tables(strTable).Rows.InsertAt(dr, 0)
       cboCombo.DataBindings.Add("DataSource", dt, dt.Tables(strTable).TableName)
       cboCombo.DataBindings.Clear()
Von Abanes
  • 706
  • 1
  • 6
  • 19
0

You can set the combo box text.

    cboCombo.DataSource = dt.Tables(strTable).DefaultView
    cboCombo.DisplayMember = strDisplayMember
    cboCombo.ValueMember = strValueMember
    cboCombo.Text = "(select an item)"

The alternative is to actually add it to your datatable before binding to the combobox.

Supposedly there is a method using reflection, but I could not get it to work.

Brian Webster
  • 30,033
  • 48
  • 152
  • 225