[英]C#: assigning text and value to combobox member
我想我曾经知道该怎么做,但是我现在无法弄清楚。 我正在尝试在具有关联值的组合框中分配一个列表项。 原因是因为我正在用数据库中的名称列表填充它,但是我希望它将主键存储为值,以便可以在后续查询中直接调用它。 例如,您从主管列表中选择一个名称,该名称将该主管的主键存储在变量中,以便在事件中使用,该事件将列出分配有该键的所有雇员作为主管。 有道理? 很标准。 这就是我只加载名称的文本部分的内容:
查询:
static string sql = "select rtrim(elname),rtrim(efname) from employee where pos_id = 2";
填充列表的代码:
try
{
conn.Open();
//determine how many records affected/returned
int records = dbAdapter.Fill(results); //fills the datatable with results and returns the number of records
if (records > 0)
{
//do something with the results (stored in the datatable)
foreach (DataRow dr in results.Rows)
{
cboSupervisor.Items.Add(dr[0] + ", " + dr[1]);
}
cboSupervisor.Sorted = true;
}
}
catch { }
这会将姓氏填入下拉列表中
最好的方法是创建一个包含要显示的信息和要保留的信息的类,然后专门设置ToString():
public class ComboItem : object
{
protected String name;
....
....
protected int id;
public ComboItem(String name, int id)
{
this.name= name;
this.id = id;
}
public override string ToString()
{
return name;
}
};
您能否使用ComboBoxItem,使用Content属性设置名称以及使用Tag属性设置值? 然后将ComboBoxItem添加到ComboBox的Items集合中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.