JimmyJimm JimmyJimm - 1 year ago 168
Vb.net Question

ListBox get value/display members

How to loop through selected items and get value member and display member of each. [multiline listbox]

LB_Sentences.DataSource = Nothing
LB_Sentences.DataSource = GetTable(False)
LB_Sentences.ValueMember = "Id"
LB_Sentences.DisplayMember = "Name"
LB_Sentences.SelectedIndex = -1

For i As Integer = 0 To LB_Sentences.SelectedItems.Count - 1
Dim id as integer = LB_Sentences.??
Dim name as integer = LB_Sentences.??

Answer Source

Firstly, while a For loop is not wrong here, a For Each loop is more appropriate.

As for the question, you can get the display member value by calling the GetItemText method. Just note that that will get the String displayed in the ListBox so, if the actual member is not type String, you're not actually getting that member's value.

With regards to the value member, there's nothing to do that for you so you have to do it yourself. Assuming that your data source is a DataTable in this case, you just have to get each item as a DataRowView and then get the value from the column as you always would. You can do the same for the display member if you need other than a String.

For Each rowView As DataRowView In myListBox.SelectedItems
    name = myListBox.GetItemText(rowView)
    id = CInt(rowView("Id"))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download