簡體   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   );
    }

選擇員工時我沒有獲得ID,消息框只是顯示我的名字...有人可以告訴我我的錯在哪里嗎? 非常感謝

在對綁定框進行數據綁定之后,您可以通過使用數據讀取器插入值來刪除綁定。 只需刪除此部分:

while (dr.Read())
{
    if(dr[0].ToString().Length > 0)
    {
        this.cbEmpName.Items.Add(dr[0].ToString());
    }
}

如果您想保留代碼,則應更改添加項的行,使其既包含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