Dharam Rai

Dharam Rai

  • NA
  • 383
  • 22.6k

Combobox item when select displaying wrong record in textbox

Jan 15 2016 4:31 AM
Hello all genius: My problem is I got two tables tbl_session where I have 'SessionID' 'SessionName' and tbl_Class where I have 'ClassID' 'SessionID' 'ClassName'  (SessionID [FK] of tbl_Class is link with Session_ID[PK] of tbl_Session ]. There are same 'ClassName' in tbl_Class whose SessionID and ClassID is different, Now my query is, if select ClassName from combobox then display ClassID in textbox. But the problem is I have same ClassName, So as per my query when I choose ClassName it shows the different ClassID, but I want to achieve the ClassID of the same ClassName that displays in my combobox.
 
Here is my code to fill combo_Class:
 
private void FillClass(int SessionID)
{
string str = "SELECT ClassId, ClassName FROM ClassMaster WHERE SessionID =@SessionID";
OleDbCommand cmd = new OleDbCommand(str, connection);
cmd.Parameters.AddWithValue("@SessionID", SessionID);
DataSet objDs = new DataSet();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
dAdapter.SelectCommand = cmd;
connection.Open();
dAdapter.Fill(objDs);
connection.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
combo_Class.ValueMember = "ClassId";
combo_Class.DisplayMember = "ClassName";
combo_Class.DataSource = objDs.Tables[0];
}
}
 
 
//And here is the code to select class from combo_Class  and display  ClassID in textbox: 
 
 
private void combo_Class_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = " select * from ClassMaster where ClassName= '" + combo_Class.Text + "' ";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txt_ClassId.Text = reader["ClassId"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
 
 // Please help me please...

Answers (14)