programmatically set the SelectedItems for a ListBox

  • Thread starter Thread starter tommcd24
  • Start date Start date
T

tommcd24

Hello all,

I need a way to read a previously saved list of customers and
programatically "Select" these items in an existing listbox. Something
to the effect of ListBox.SelectedItems = myCollection. Of course
SelectedItems is readonly.

I'm reading in from an XML file and I have that portion of the issue
resolved. Where I run into problems is how to get them all selected.

Any suggestions?
 
tommcd24 said:
Hello all,

I need a way to read a previously saved list of customers and
programatically "Select" these items in an existing listbox.
Something to the effect of ListBox.SelectedItems = myCollection. Of
course SelectedItems is readonly.

I'm reading in from an XML file and I have that portion of the issue
resolved. Where I run into problems is how to get them all selected.

Any suggestions?


lbx.SetSelected(.., True)



Armin
 
Thanks Armin,

SetSelected wants an index and I'm difficulty translating the values
from my xml file which correspond to the ValueMember property of the
listbox items. I've looked into ListBox.FindString() and
ListBox.IndexOf() but both return -1. I'm guessing they must be
searching the DisplayMember property.

Any thoughts on how to translate from the ValueMember values to Index?
 
Does anyone have suggestions or sample code to do this? I need to be
able to Select listbox items based on the item value.

Thanks in advance,
 
tommcd24 said:
Does anyone have suggestions or sample code to do this? I need to be
able to Select listbox items based on the item value.

I don't know if you're looking for a routine below or not to set the combox
to the display is display value based based on its item value or not, but it
might help you, possibly.


Sub SelectCBOBbyItem(ctrl as Combobox, someval as whatevertype)

dim i as Integer
For i = 0 To ComboBox1.Items.Count - 1

ComboBox1.SelectedIndex = i

If ComboBox1.SelectedValue = someval Then exit sub

Next

end sub
 
Oops, you would be using the ctrl

call SelectCBOBbyItem(Combox1, value)

Sub SelectCBOBbyItem(ctrl as Combobox, someval as whatevertype)

dim i as Integer
For i = 0 To ctrl.Items.Count - 1

ctrl.SelectedIndex = i

If ctrl.SelectedValue = someval Then exit sub

Next

end sub
 
I was overcomplicating this issue. I was assuming that
ListBox.SelectedValue could only hold 1 value. On a lark I tried
repeated calls using that property and achieved the result I needed of
selecting multiple items based on the ValueMember. I'm including my
code below for others who may have similar situations.

Using xReader As XmlReader = XmlReader.Create(strFilePath & "\"
& strFileName)
xReader.ReadStartElement("Customers")
While xReader.Read()
If (xReader.IsStartElement()) Then
If (xReader.IsEmptyElement()) Then
Me.lstCustomers.SelectedValue = xReader(0)
End If
End If
End While
End Using
 
Back
Top