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)
开发者_如何学JAVA {
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():
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? Then add the ComboBoxItem to your ComboBox's Items collection?
精彩评论