Reputation: 580
private void frmNSS5_Load(object sender, System.EventArgs e)
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
con = new SqlConnection(@"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True; initial catalog=CleanPayrollTest2");
cmd = new SqlCommand("SELECT IsNull(ArEmpName,'') + ' ' + IsNull(ArFatherName,'') + ' ' + IsNull(ArLastName,'') as EmpName, ID as ID FROM [Emp] ", con);
try
{
con.Open();
dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
this.cbEmpName.ValueMember = "ID".ToString();
this.cbEmpName.DisplayMember = "EmpName";
this.cbEmpName.DataSource = ds.Tables["EmpName"];
while (dr.Read())
{
if(dr[0].ToString().Length > 0)
{
this.cbEmpName.Items.Add(dr[0].ToString());
}
}
con.Close();
}
catch
{
MessageBox.Show("Connection Failed");
}
}
private void comboEmpName_SelectedIndexChanged(object sender, System.EventArgs e)
{
MessageBox.Show("Emp ID:" + ' ' + this.cbEmpName.SelectedValue + ", " + "EmpName:" + ' ' + this.cbEmpName.SelectedItem );
}
I'm not getting the ID while selecting an employee, the messssage box just show me the name... Can someone tell me where's my fault? Thank you so much
Upvotes: 1
Views: 6896
Reputation: 286
Try this
this.cbEmpName.Items.Add(new ListItem(dr[0].ToString(),dr[4].ToString()));
Upvotes: 0
Reputation: 50672
After databinding the combobox you delete the binding by inserting the values using a datareader. Just remove this part:
while (dr.Read())
{
if(dr[0].ToString().Length > 0)
{
this.cbEmpName.Items.Add(dr[0].ToString());
}
}
If you want to keep the code you should change the line that adds the item so it includes both the Value and the display data:
this.cbEmpName.Items.Add(
new { EmpName = dr[0].ToString(), ID = dr[1].ToString()});
Upvotes: 1