You can show one element to the user such as the name, but use a different one for the code to identify the item using DisplayMember
and ValueMember
Dim SQL = "SELECT Id, Name FROM GroupCode ORDER BY Name"
...
GrpDT = New DataTable
GrpDT.Load(cmd.ExecuteReader)
cboGroup.DataSource = GrpDT
cboGroup.DisplayMember = "Name"
cboGroup.ValueMember = "Id"
The user will only see the names, while the code can use ValueMember
:
Private Sub cboGroup_SelectedValueChanged(...etc
Console.WriteLine(cboGroup.SelectedValue)
End Sub
It prints the Group ID not the name. Depending on the ORDER BY clause in the SQL and the ID, the SelectedIndex
may or may not match, so respond to SelectedValueChanged
event. If you use SelectedValue
instead of SelectedItem
you wont have to thrash about with a DataRowView
item.
Note that SelectedValue
is Object
so you will have to cast to integer or whatever for use elsewhere.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…