显示数组列表项的 C# 组合框
本文关键字:组合 数组 列表 显示 | 更新日期: 2023-09-27 18:32:53
我希望我的组合框列出我所有的数组列表项。这就是我到目前为止所拥有的,但我不知道我可以添加什么来使其将每个数组列表项显示在组合框中。有没有办法写Items.Display或类似的东西?
public void eh()
{
snip
}
public void PopulateActors()
{
cboActor.Items.Clear();
cboActor.Items.AddRange(ActorArrayList.Cast<string>());
}
您可以使用DataSource
将ArrayList
绑定到组合框:
yourComboBox.DataSource = yourArrayList;
使用DisplayMember
和ValueMember
选择显示的内容以及作为项目Value
评估的内容:
yourComboBox.DisplayMember = "Displayed thing";
youtComboBox.ValueMember = "Evaluated thing";
如果未指定 DisplayMember
,则将在每个项目上调用 ToString()
以获取显示的字符串。在您的情况下,看起来您有一个字符串ArrayList
,因此您无需为 DisplayMember
和 ValueMember
指定任何值。
注意:您应该改用List<T>
,它会更好。 ArrayList
只是一个旧东西。
你可以像这样创建一个数组列表
ArrayList sampleArray = new ArrayList();
sampleArray.Add("India");
sampleArray.Add("China");
sampleArray.Add("USA");
sampleArray.Add("UK");
sampleArray.Add("Japan");
然后可以将其添加到您的组合框中
cboActor.Items.Clear();
cboActor.Items.AddRange(sampleArray.ToArray());
您需要在循环中创建 ComboBoxItems 并逐个添加它们:
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
cboActor.Items.Add(item);
希望这对:)有所帮助
foreach (string line in ActorArrayList)
{
cboActor.Items.Add(line);
}
你必须添加一个列表项目(文本,值)
foreach (Actor line in ActorArrayList)
{
cboActor.Items.Add(new ListItem( line.Name ,line.ID)); //as second part you may enter the ID of the object so you can use it at a later time
}
}
上面没有提到的另一个例子!与 Sid M 类似,由于这对我不起作用,我分享了我为我找到的解决方案:
String[] data = new String[]{"Data1", "Data2", "Data3", "Data4"};
cboData.Items.AddRange(data);