在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
当前回答
这类似于其他一些答案,但是很紧凑,如果已经有一个列表,就避免了转换到字典。
给定一个窗口窗体上的ComboBox“ComboBox”和一个具有字符串类型属性Name的类SomeClass,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
这意味着SelectedItem是list中的SomeClass对象,并且组合框中的每个项目将使用其名称显示。
其他回答
您可以使用字典对象,而不是创建自定义类来在组合框中添加文本和值。
在Dictionary对象中添加键和值:
Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");
将源Dictionary对象绑定到Combobox:
comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
检索键和值:
string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;
完整来源:组合框文本和值
这类似于其他一些答案,但是很紧凑,如果已经有一个列表,就避免了转换到字典。
给定一个窗口窗体上的ComboBox“ComboBox”和一个具有字符串类型属性Name的类SomeClass,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
这意味着SelectedItem是list中的SomeClass对象,并且组合框中的每个项目将使用其名称显示。
我有同样的问题,我所做的是添加一个新的ComboBox,只有在相同的索引值,然后第一个,然后当我改变主要组合的索引在第二个改变的同时,然后我取第二个组合的值,并使用它。
这是代码:
public Form1()
{
eventos = cliente.GetEventsTypes(usuario);
foreach (EventNo no in eventos)
{
cboEventos.Items.Add(no.eventno.ToString() + "--" +no.description.ToString());
cboEventos2.Items.Add(no.eventno.ToString());
}
}
private void lista_SelectedIndexChanged(object sender, EventArgs e)
{
lista2.Items.Add(lista.SelectedItem.ToString());
}
private void cboEventos_SelectedIndexChanged(object sender, EventArgs e)
{
cboEventos2.SelectedIndex = cboEventos.SelectedIndex;
}
如果有人仍然对此感兴趣,这里有一个简单而灵活的类,用于具有文本和任何类型的值的组合框项目(非常类似于Adam Markowitz的例子):
public class ComboBoxItem<T>
{
public string Name;
public T value = default(T);
public ComboBoxItem(string Name, T value)
{
this.Name = Name;
this.value = value;
}
public override string ToString()
{
return Name;
}
}
使用<T>比将值声明为对象要好,因为使用object,您必须跟踪用于每个项的类型,并在代码中强制转换以正确使用它。
我已经在我的项目中使用了很长一段时间了。它真的很方便。
我喜欢fab的答案,但不想为我的情况使用字典,所以我替换了一个元组列表。
// set up your data
public static List<Tuple<string, string>> List = new List<Tuple<string, string>>
{
new Tuple<string, string>("Item1", "Item2")
}
// bind to the combo box
comboBox.DataSource = new BindingSource(List, null);
comboBox.ValueMember = "Item1";
comboBox.DisplayMember = "Item2";
//Get selected value
string value = ((Tuple<string, string>)queryList.SelectedItem).Item1;