我有一个多选模式的System.Windows.Forms.ListBox和一组我想要选择的项目。我该怎么做?
[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);
}
答案 0 :(得分:3)
这样做:
selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));
有关:
[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);
}