Amin
Amin

Reputation: 172

Load Data from SQL Server into a combobox

I tried to get data from SQL Server (2 tables: Famille and Compte) into 2 comboboxes in the Form_Load().

But as you see the result, it works with the 1st combobox, but the 2nd it shows System.Data.SqlClient.SqlDataReader

enter image description here

This is the Code

private void Tresorerie_Load(object sender, EventArgs e)
{
        conn = new SqlConnection(connstring);
        conn.Open();
        String queryCompte = "select NomCom from Compte";
        String queryFamille = "select NomFam from Famille";
        commCompte = new SqlCommand(queryCompte, conn);
        commFamille = new SqlCommand(queryFamille, conn);

        try
        {
            //Compte
            commCompte.CommandType = CommandType.Text;
            dreaderCompte = commCompte.ExecuteReader();

            while (dreaderCompte.Read())
            {
                queryCompte = dreaderCompte[0].ToString();
                TreComBoxCompte.Items.Add(queryCompte);
            }
        }
        catch (Exception)
        {
            MessageBox.Show("Problem with load Compte");
        }
        finally
        {
            dreaderCompte.Close();
        }

        try
        {
            //Famille
            commFamille.CommandType = CommandType.Text;
            dreaderFamille = commFamille.ExecuteReader();

            while (dreaderFamille.Read())
            {
                queryFamille = dreaderFamille[0].ToString();
                TreComBoxFamille.Items.Add(dreaderFamille);
            }
        }
        catch (Exception)
        {
            MessageBox.Show("Problem with load Famille");
        }
        finally
        {
            dreaderFamille.Close();
        }
        conn.Close();
    }

Upvotes: 1

Views: 142

Answers (3)

Juran
Juran

Reputation: 177

You should do it like this:

while (dreaderFamille.Read())
{
    queryFamille = dreaderFamille[0].ToString();
    TreComBoxFamille.Items.Add(queryFamille);
}

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125332

For second combobox you are adding your datareader dreaderFamille:

TreComBoxFamille.Items.Add(dreaderFamille);

while you should add queryFamille:

queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);

If you pay attention to item texts in your ComboBox you will guess the problem and when you look at code, you will see your guess is true.

Upvotes: 5

Jigneshk
Jigneshk

Reputation: 348

for 2nd comboxbox, you are using wrong object to add

TreComBoxFamille.Items.Add(queryFamille);

Upvotes: 0

Related Questions