I have a System.Windows.Forms.ListBox in multiple selection mode and a set of items I'd like to be selected. How do I do that?
[Test]
public void SetListBox()
{
var listBox = new ListBox();
var items = new List<string>{"one", "two", "three", "four"};
listBox.SelectionMode = SelectionMode.MultiSimple;
listBox.Items.AddRange(items.ToArray());
var selectedItems = new List<string> {"two", "four"};
// ???
Assert.AreEqual(selectedItems, listBox.SelectedItems);
}
Do this:
selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));
For:
[Test]
public void SetListBox()
{
var listBox = new ListBox();
var items = new List<string>{"one", "two", "three", "four"};
listBox.SelectionMode = SelectionMode.MultiSimple;
listBox.Items.AddRange(items.ToArray());
var selectedItems = new List<string> {"two", "four"};
selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));
Assert.AreEqual(selectedItems, listBox.SelectedItems);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.