gpt4 book ai didi

c# - 组合框和通用列表

转载 作者:行者123 更新时间:2023-11-30 17:21:34 25 4
gpt4 key购买 nike

我有一个 list

 List<string> strArraylist = new List<string>();

我想给它添加一个组合框的值..

最佳答案

更新:我刚刚意识到您可能一直在问我下面提供的内容的相反:如何从 ComboBox 添加项目 一个 List<string> 。如果是这种情况,您总是可以这样做:

List<string> strList = new List<string>();
strList.AddRange(cbx.Items.Cast<object>().Select(x => x.ToString()));

这是我使用的扩展方法:

public static class ControlHelper
{
public static void Populate<T>(this ComboBox comboBox, IEnumerable<T> items)
{
try
{
comboBox.BeginUpdate();
foreach (T item in items)
{
comboBox.Items.Add(item);
}
}
finally
{
comboBox.EndUpdate();
}
}
}

这允许您使用任何可以枚举的通用集合来填充 ComboBox。看看打电话是多么容易:

List<string> strList = new List<string> { "abc", "def", "ghi" };
cbx.Populate(strList);

请注意,您还可以将此方法设为非泛型,因为 ComboBox.Items 属性属于非泛型类型(您可以将任何 object 添加到 Items )。在这种情况下,Populate 方法将接受普通的 IEnumerable 而不是 IEnumerable<T>

关于c# - 组合框和通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3254679/

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