[英]C#: assigning text and value to combobox member
I think i knew how to do this once upon a time but I can't figure it out right now. 我想我曾经知道该怎么做,但是我现在无法弄清楚。 I'm trying to assign a list item in a combo box that has an associated value.
我正在尝试在具有关联值的组合框中分配一个列表项。 Reason being is because i am populating it with a list of names from a database but I want it to store the primary key as a value so that I can call it directly in a subsequent query.
原因是因为我正在用数据库中的名称列表填充它,但是我希望它将主键存储为值,以便可以在后续查询中直接调用它。 For example, you select a name from a list of supervisors which will store the primary key for that supervisor in a variable for use in an event that will list all employees that have that key assigned to them as a supervisor.
例如,您从主管列表中选择一个名称,该名称将该主管的主键存储在变量中,以便在事件中使用,该事件将列出分配有该键的所有雇员作为主管。 That make sense?
有道理? Pretty standard.
很标准。 Here's what I have that is loading just the text portion of the names in:
这就是我只加载名称的文本部分的内容:
The query: 查询:
static string sql = "select rtrim(elname),rtrim(efname) from employee where pos_id = 2";
The code that populates the list: 填充列表的代码:
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 { }
This fills the dropdown with lastname, firstname 这会将姓氏填入下拉列表中
The best way is create a class containing the information you want to display and the one you want to keep, then specialize ToString(): 最好的方法是创建一个包含要显示的信息和要保留的信息的类,然后专门设置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;
}
};
Could you use a ComboBoxItem, use the Content Property to set the name, and use the Tag Property to set the Value? 您能否使用ComboBoxItem,使用Content属性设置名称以及使用Tag属性设置值? Then add the ComboBoxItem to your ComboBox's Items collection?
然后将ComboBoxItem添加到ComboBox的Items集合中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.