'Get Primary Key of the table From Combo Box
I'm using this method to fetch foreign key from Table Teachers. Combo box have teachers name. Whenever I changed the selectoin It shows the name of the selected teacher in txtname.Text. But the message box inside while loop is not popping Up.
private void cmbTeacher_SelectedIndexChanged(object sender, EventArgs e)
{
string Tname = cmbTeacher.SelectedItem.ToString();
con.Open();
string qbc = "Select TeacherID from Teachers where Name = ' " + Tname + " ' ";
SqlCommand cmda = new SqlCommand(qbc, con);
SqlDataReader drat = cmda.ExecuteReader();
while (drat.Read())
{
textTeacherID.Text = drat[0].ToString();
MessageBox.Show(drat[0].ToString());
}
con.Close();
txtname.Text = cmbTeacher.SelectedItem.ToString();
}
Actually drop down list of Combo box is a column of name from table Teachers. When a user select the teacher from the drop down list I want to fetch the primary key of that teacher. Look at this Code
// Teacher Table
con.Open();
String qt = "Select Name, TeacherID from Teachers";
SqlCommand cmdt = new SqlCommand(qt, con);
SqlDataReader drt = cmdt.ExecuteReader();
while (drt.Read())
{
cmbTeacher.Items.Add(drt["Name"].ToString());
cmbTeacher.DisplayMember = (drt["Name"].ToString());
cmbTeacher.ValueMember = (drt["TeacherID"].ToString());
cmbTeacher.Text = "Select Teacher";
}
con.Close();
How Can I get the primary key of that Teacher???
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
