Bèlguesmi Sémah Bèlguesmi Sémah - 3 months ago 11
C# Question

save a text and a value into combobox from a database table

I want to take the name and surname of users from the table "EMPLOYE" (SQL DB) and save them in the combobox.
I want to save the ID of each user in the combobox value.
so this is my code =>

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

}


The full name displayed without problems but the value no !!
The problem is that the combobox3.ValueMember take the string "ID_EMP" not the value from the table EMPLOYE !

ANY SOLUTIONS PLEASE ?

Answer

Edit your sql query like this. Should work

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

        }