更新时间:2023-01-28 11:12:24
Winforms 中不存在您习惯的属性,但由于 ComboBox
接受一个对象,您可以创建自己的具有您需要的属性的自定义类.我已经在 ListControl.DisplayMember 上获取了 MSDN 文档属性,并以修改为例.
The properties that you are used to are not present in Winforms, but since the ComboBox
takes an object, you can make your own Custom Class with the Properties that you need. I have taken the MSDN Documentation on the ListControl.DisplayMember Property and modified it as an example.
它的作用是创建一个名为 customComboBoxItem
的自定义类,其中包含一个 Text
和一个 Value
属性,然后我创建一个 List 并分配它作为 ComboBox
的 DataSource
,将 Text
属性指定为 DisplayMember.看看这对你是否可行.
What it does is create a custom class called customComboBoxItem
with a Text
and a Value
Property, I then make a List and assign it as the DataSource
of your ComboBox
assigning the Text
Property as the DisplayMember. See if this is workable for you.
public partial class Form1 : Form
{
List<customComboBoxItem> customItem = new List<customComboBoxItem>();
public Form1()
{
InitializeComponent();
customItem.Add(new customComboBoxItem("text1", "id1"));
customItem.Add(new customComboBoxItem("text2", "id2"));
customItem.Add(new customComboBoxItem("text3", "id3"));
customItem.Add(new customComboBoxItem("text4", "id4"));
comboBox1.DataSource = customItem;
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show( ((customComboBoxItem)comboBox1.SelectedItem).Text + " "
+ ((customComboBoxItem)comboBox1.SelectedItem).Value);
}
}
public class customComboBoxItem
{
private string text;
private string value;
public customComboBoxItem(string strText, string strValue)
{
this.text = strText;
this.value = strValue;
}
public string Text
{
get { return text; }
}
public string Value
{
get { return value; }
}
}