You can try the following approach assuming you have loaded the data from the SQL query into a
DataTable
.
(If not see
Populating a DataSet from a DataAdapter[
^])
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Donald Duck");
dt.Rows.Add(2, "Donald Trump");
dt.Rows.Add(3, "Duffy Duck");
comboBox1.DataSource = dt;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";
This way the
Name
will be shown in the combo box, and the
Id
is accessible as well.
For example:
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drv = (comboBox1.SelectedItem as DataRowView);
if (drv != null)
{
DataRow dr = drv.Row;
int id = (int)dr["Id"];
string name = dr["Name"].ToString();
textBox1.Text = dr["Name"].ToString(); }
}