我有表 - 自定义 ID(如 1.10、1.20)和名称(值可以重复的字符串)。我的问题是将它设置为组合框之类的 winForms 控件。但我希望该字段中的用户只会看到名称,而 id 将不可见,但下意识地应该连接到控件中的名称,以便当用户在组合框中选择项目时,我可以获得此 id。
知道这是可能的吗?
请您参考如下方法:
像这样设置组合框:
// item type to display in the combobox
public class Item
{
public int Id { get; set; }
public string Text { get; set; }
}
// build new list of Items
var data = List<Item>
{
new Item{Id = 1, Text = "Item 1"},
new Item{Id = 2, Text = "Item 2"},
new Item{Id = 3, Text = "Item 3"}
};
// set databind
comboBox1.DataSource = data;
comboBox1.ValueMember = "Id"; // the value of a list item should correspond to the items Id property
comboBox1.DisplayMember = "Text"; // the displayed text of list item should correspond to the items Id property
// get selected value
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = comboBox1.SelectedValue;
}
