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,messssage框只顯示我的名字......有人能告訴我我的錯在哪裏?非常感謝你從組合框中獲取選定值的ID
什麼是「ID」.ToString()'??? :D – yogi
您正在選擇ID和名稱,但您只是在'while'中添加名稱。你的'DataSet'和'DataTable'也是未使用的,''ID「.ToString()'很有趣。您還應該使用'using'語句來進行連接和數據讀取器,以確保它們在異常情況下也能被處置(關閉)。 –
對不起,Tostring的東西已經被添加了錯誤.. – Nejthe