ComboBox:向项目添加文本和值(无绑定源) [英] ComboBox: Adding Text and Value to an Item (no Binding Source)
本文介绍了ComboBox:向项目添加文本和值(无绑定源)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C# WinApp 中,如何将 Text 和 Value 添加到 ComboBox 的项目中?我做了一个搜索,通常答案是使用绑定到源"..但就我而言,我的程序中没有准备好绑定源......我该如何做这样的事情:
In C# WinApp, how can I add both Text and Value to the items of my ComboBox? I did a search and usually the answers are using "Binding to a source".. but in my case I do not have a binding source ready in my program... How can I do something like this:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
推荐答案
您必须创建自己的类类型并覆盖 ToString() 方法以返回您想要的文本.下面是一个您可以使用的类的简单示例:
You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
以下是其用法的简单示例:
The following is a simple example of its usage:
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());
}
这篇关于ComboBox:向项目添加文本和值(无绑定源)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文