在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
当前回答
我喜欢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;
其他回答
您必须创建自己的类类型并重写ToString()方法以返回所需的文本。下面是一个你可以使用的类的简单例子:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
下面是它使用的一个简单例子:
private void Test()
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
你可以使用泛型类型:
public class ComboBoxItem<T>
{
private string Text { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Text;
}
public ComboBoxItem(string text, T value)
{
Text = text;
Value = value;
}
}
使用简单int-Type的示例:
private void Fill(ComboBox comboBox)
{
comboBox.Items.Clear();
object[] list =
{
new ComboBoxItem<int>("Architekt", 1),
new ComboBoxItem<int>("Bauträger", 2),
new ComboBoxItem<int>("Fachbetrieb/Installateur", 3),
new ComboBoxItem<int>("GC-Haus", 5),
new ComboBoxItem<int>("Ingenieur-/Planungsbüro", 9),
new ComboBoxItem<int>("Wowi", 17),
new ComboBoxItem<int>("Endverbraucher", 19)
};
comboBox.Items.AddRange(list);
}
不知道这是否适用于原始帖子中给出的情况(不要介意这是两年后的事实),但这个例子对我来说是适用的:
Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");
foreach (DictionaryEntry ImageType in htImageTypes)
{
cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";
要读取回值,必须将SelectedItem属性转换为DictionaryEntry对象,然后可以计算该对象的Key和value属性。例如:
DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);
这里有更好的解决方案;
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());
您应该在运行时使用动态对象来解析组合框项。
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new { Text = "Text", Value = "Value" });
(comboBox.SelectedItem as dynamic).Value