简体   繁体   中英

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? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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