문제

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