在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
当前回答
您可以使用此代码将一些项插入到具有文本和值的组合框中。
C#
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
combox.Items.Insert(0, "Copenhagen");
combox.Items.Insert(1, "Tokyo");
combox.Items.Insert(2, "Japan");
combox.Items.Insert(0, "India");
}
XAML
<ComboBox x:Name="combox" SelectionChanged="ComboBox_SelectionChanged_1"/>
其他回答
这里有更好的解决方案;
Dictionary<int, string> userListDictionary = new Dictionary<int, string>();
foreach (var user in users)
{
userListDictionary.Add(user.Id,user.Name);
}
cmbUser.DataSource = new BindingSource(userListDictionary, null);
cmbUser.DisplayMember = "Value";
cmbUser.ValueMember = "Key";
检索数据
MessageBox.Show(cmbUser.SelectedValue.ToString());
这是一个非常简单的解决方案为windows窗体,如果所有需要的是最终值(字符串)。项目的名称将显示在组合框上,选择的值可以很容易地进行比较。
List<string> items = new List<string>();
// populate list with test strings
for (int i = 0; i < 100; i++)
items.Add(i.ToString());
// set data source
testComboBox.DataSource = items;
并在事件处理程序上获取所选值的值(字符串)
string test = testComboBox.SelectedValue.ToString();
这类似于其他一些答案,但是很紧凑,如果已经有一个列表,就避免了转换到字典。
给定一个窗口窗体上的ComboBox“ComboBox”和一个具有字符串类型属性Name的类SomeClass,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
这意味着SelectedItem是list中的SomeClass对象,并且组合框中的每个项目将使用其名称显示。
Visual Studio 2013是这样做的:
单一项目:
comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(1) { L"Combo Item 1" });
多个项目:
comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(3)
{
L"Combo Item 1",
L"Combo Item 2",
L"Combo Item 3"
});
不需要重写类或包含任何其他内容。是的,comboBox1->SelectedItem和comboBox1->SelectedIndex调用仍然有效。
这是我想到的方法之一:
combo1.Items。添加(new ListItem("Text", "Value"))
要更改一个项目的文本或值,你可以这样做:
combo1.Items[0].Text = 'new Text';
combo1.Items[0].Value = 'new Value';
在Windows窗体中没有名为ListItem的类。它只存在于ASP中。因此,在使用它之前,您需要编写自己的类,就像@Adam Markowitz在他的回答中所做的一样。
还可以查看这些页面,它们可能会有帮助:
如何将项目添加到组合框 如何:从Windows窗体组合框、列表框或checkkedlistbox控件中添加和删除项