user9153800
user9153800

Reputation: 15

How to populate two or more comboboxes from a single select query in C#

I want to populate my two comboboxes from a single query like only the first combobox is being populated.

Here is my code:

private void loadcourses()
{
    try
    {
        using (sqlcon)
        {
            sqlcon.Open();
            coursecmd = new SqlCommand("SELECT * FROM DegCourses", sqlcon);                 
            reader = coursecmd.ExecuteReader();
            if (reader.HasRows)
            {
                while(reader.Read())
                cmbcoursecode.Items.Add(reader.GetString(1));
                cmbcoursedesc.Items.Add(reader.GetString(2));
            }
            reader.Close();
        }                
    }
    catch (Exception) { }
}

When I execute this code, it only populates the first combobox, cmbcoursecode -- the other does not populate.

Can you help me please?

Upvotes: 0

Views: 41

Answers (1)

PSK
PSK

Reputation: 17943

If you don't specify curly braces to your while loop, in that case the scope of the while will be just the next statement. Change your while like following

while(reader.Read()) 
{
   cmbcoursecode.Items.Add(reader.GetString(1));
   cmbcoursedesc.Items.Add(reader.GetString(2));
}

Upvotes: 2

Related Questions