Search code examples
vb.netdatagridcomboboxcolumnvaluemember

display/value member not changing with selected index of combo box


A datagridview(Mydgv1) is created on run time. The first column in it is an editable combo box column.I have set the display member and value member for it, but i am not able to fetch the right display/value member. When I choose an item from its drop down, i get the value of value/display member as the value/display member of the last item in the drop down.Why isn't the value /display member changing with the selected item in combo box column.

On Form Load Event

combo.HeaderText = "Item"
combo.Name = "itemid"
combo.Items.Clear()
Dim ds As SqlDataReader
Dim cmm As New SqlCommand("select itemid from itemdesc", con)
con.Open()
    ds = cmm.ExecuteReader
    If ds.HasRows Then
        While ds.Read
            combo.Items.Add(ds(0).ToString)
            combo.ValueMember = ds("itemid")
            combo.DisplayMember = ds("itemid")
        End While
    End If
con.Close()
Mydgv1.Columns.Add(combo)

On comboboxcolumn's Leave Event

it = combo.DisplayMember
MsgBox(it)

Solution

  • do not refer to the displaymember itself and use the SelectedIndexChanged Event to retrieve the selected values

    Private Sub combo_SelectedIndexChanged(sender as Object, e as EventArgs) Handels combo.SelectedIndexChanged
    
        'because your display and valuemember are set as the same
        MsgBox(combo.SelectedValue.ToString)
        'if you want the displaymember as the result use
        MsgBox(combo.Text)
    
    End Sub