从组合框中获取所选值的ID
本文关键字:ID 获取 组合 | 更新日期: 2023-09-27 17:51:08
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 );
}
我没有得到ID,而选择一个员工,消息框只是显示我的名字…谁能告诉我我的错在哪里?非常感谢
将组合框绑定后,通过使用数据读取器插入值来删除绑定。只需删除这部分:
while (dr.Read())
{
if(dr[0].ToString().Length > 0)
{
this.cbEmpName.Items.Add(dr[0].ToString());
}
}
如果你想保留代码,你应该改变添加项目的行,使它包括值和显示数据:
this.cbEmpName.Items.Add(
new { EmpName = dr[0].ToString(), ID = dr[1].ToString()});
试试这个
this.cbEmpName.Items.Add(new ListItem(dr[0].ToString(),dr[4].ToString()));