简体   繁体   English

从组合框中获取所选值的ID

[英]Get the ID of the selected value from a combobox

    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? 选择员工时我没有获得ID,消息框只是显示我的名字...有人可以告诉我我的错在哪里吗? Thank you so much 非常感谢

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: 如果您想保留代码,则应更改添加项的行,使其既包含Value也包含显示数据:

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM