gpt4 book ai didi

c# - 如何在 WinForms ListBox 上设置多个选定项

转载 作者:行者123 更新时间:2023-11-30 22:00:51 26 4
gpt4 key购买 nike

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

最佳答案

这样做:

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

关于c# - 如何在 WinForms ListBox 上设置多个选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com