如何在WinForms ListBox上设置多个选定的项目

时间:2015-01-29 16:07:06

标签: c# winforms listbox

我有一个多选模式的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);
}

1 个答案:

答案 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);
    }