Вопрос

i have a listbox with 3 listitems (bob, peter, john). How do I make the listitems selected/highlighted depending on what is applicable in the array. Currently I have this:

string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');

for (int i = 0; i < selectedName.Length; i++)
{
  lbName.SelectedIndex = lbName.Items.IndexOf(lbName.Items.FindByValue(selectedName[i]));
}

But it only highlights the last item in the array. e.g. selectedName consist of 2 names (bob and john), but only john is highlighted

Это было полезно?

Решение

First you should check if lbName.SelectionMode is ListSelectionMode.Multiple

then you should the following

string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');

lbName.SelectedIndex = -1;

foreach (var name in selectedName)
{
    lbName.Items.First(item => item.Value == name).Selected = true;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top