Shalvin.Com                                                                                                                      Home

Filling ComboBox with DataReader and obtaining the primary key of selected item



SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;

private void Form1_Load(object sender, EventArgs e) {
 cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
 cnn.Open(); cmd = new SqlCommand("select * from Categories", cnn);
 dr = cmd.ExecuteReader();
 while (dr.Read())
  cboCategories.Items.Add(dr["CategoryName"]);

 dr.Close();
}

private void cboCategories_SelectedIndexChanged(object sender, EventArgs e)
{
 cmd = new SqlCommand("select CategoryId from Categories where CategoryName = '" + cboCategories.Text + "'", cnn); 
 dr = cmd.ExecuteReader();
 while (dr.Read())
  MessageBox.Show(dr["CategoryId"].ToString());

 dr.Close();
}


Contact : shalvin@gmail.com