我想从表格" EMPLOYE"中取出用户的姓名和姓氏。 (SQL DB)并将它们保存在组合框中。 我想在组合框值中保存每个用户的ID。 所以这是我的代码=>
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP, concat(NOM_EMP,' ',PRENOM_EMP) as 'nom_prenom' from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = "nom_prenom";
comboBox3.ValueMember = "ID_EMP";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
显示的全名没有问题,但值为no !! 问题是combobox3.ValueMember接受字符串" ID_EMP"不是表EMPLOYE的价值!
任何解决方案请?
答案 0 :(得分:1)
像这样编辑你的SQL查询。应该工作
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP,(NOM_EMP+ ' ' + PRENOM_EMP) AS NOMM from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = "NOMM";
comboBox3.ValueMember = "ID_EMP";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
答案 1 :(得分:1)
要获得值,请尝试
MessageBox.Show(comboBox3.SelectedValue.ToString())
答案 2 :(得分:0)
列名是您想要使用的问题列索引请参见此处。
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP,(NOM_EMP+ ' ' + PRENOM_EMP) AS NOMM from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = dt.Columns[1].ColumnName;
comboBox3.ValueMember = dt.Columns[0].ColumnName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}