VB.NET Combobox Valuemember

Hi,

I want to bind the primary id to combobox.valuemember so that i can retrieve it by using combobox.selectvalue. But i get return value is blank. Only the combobox.selecteditem has value. I have no idea. Please advise. Thank you.


  Private Sub CUSTOMERComboBox_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CUSTOMERComboBox.SelectedValueChanged
  Dim ConnString As String = My.Settings.dbConnectionString
        Dim SQLString2 As String = "SELECT SITE.ID,DEBTOR_SITE.ID, SITE.SITENO, SITE.DESCRIPTION FROM DEBTOR_SITE INNER JOIN SITE ON DEBTOR_SITE.SITE_ID = SITE.ID WHERE (DEBTOR_SITE.DEBTOR_ID = '" & DEBTORComboBox.SelectedItem & "' AND DEBTOR_SITE.CUSTOMER_ID = '" & CUSTOMERComboBox.SelectedItem & "')"
        Dim OleDBConn2 As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(ConnString)
        Dim DataSet2 As New DataSet()
        Dim OleDbDataAdapter2 As System.Data.OleDb.OleDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQLString2, OleDBConn2)
        OleDBConn2.Open()
        OleDbDataAdapter2.Fill(DataSet2, "DEBTOR_SITE")

        Dim DataTable2 As New DataTable()
        DataTable2 = DataSet2.Tables("DEBTOR_SITE")

        SITEComboBox.Items.Clear()

        Dim i As Integer
        For i = 0 To DataTable2.Rows.Count - 1
            SITEComboBox.ValueMember = DataTable2.Rows(i).Item(1)
            SITEComboBox.DisplayMember = DataTable2.Rows(i).Item(2)
            SITEComboBox.Items.Add(DataTable2.Rows(i).Item(2))
        Next
    End Sub

Bind to the combobox instead of in the loop:

SITEComboBox.DataSource = DataTable2
SITEComboBox.DataBind()

Then just make sure the the ValueMember and DisplayMember are set as attributes on the asp:ComboBox.

If you really wana do it in the loop, You need to create a new ListItem instance. Set the values and then add it to the list:


Dim i As Integer
        For i = 0 To DataTable2.Rows.Count - 1
            Dim newItem As ListItem
            newItem.Value = DataTable2.Rows(i).Item(1)
            newItem.Text= DataTable2.Rows(i).Item(2)
            SITEComboBox.Items.Add(newItem)
        Next


You can also set the value and text in the constructor of the declaration, but i dnt no VB that well to give you that sintax
ListItem newItem = new ListItem(“text”,“value”);

I hope this helps

NightStalker-DNS & chunket,

Code worked fine for me, but the only issue I have is that in SITEComboBox_SelectedIndexChanged, I want to proceed with the selected value from combo box and for that I am using
cboType.SelectedValue.ToString(),

But this doesn’t work!

Any suggestions?

What if you try cboType.SelectedItem.Value?