I'm having issues with setting selected items in a listbox from a comma separated data list.
The comma delimited list has values like this (valueList): A,B,C,D
List<string> values = valueList.Split(',').ToList();
foreach(string val in values)
{
listBox.SelectedItems.Add(val);
}
Basically I loop through the items in the delimited list and attempt to set the selected items in the listbox (which contains the items A, B, C, D, E, F). With this code, I suspected it would select items A-D in the list box, but it doesn't highlight/select any items.
Any ideas?
Since you have already have items in your ListBox and on you want to select only those returned by the string.Split operation then use ListBox.SetSelected method like:
var valueArray = valueList.Split(',');
for (int i = 0; i < listBox.Items.Count; i++)
{
if (valueArray.Contains(listBox.Items[i].ToString()))
{
listBox.SetSelected(i, true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With