Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set listbox selected items from comma separated list

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?

like image 512
Zach Avatar asked Jul 23 '26 04:07

Zach


1 Answers

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);
    }
}
like image 164
Habib Avatar answered Jul 25 '26 18:07

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!