Search code examples
winformsvisual-studio-2010comboboxdatasourcelocal-database

Populating a Combo Box


I created a Windows Form, with a ComboBox, and a Local Database in Visual Studio 2010. The database has a table with a column whose rows I want to list in the combo box. How can I achieve this?

I tried adding a data source with the column I am interested in through the IDE, but it did not work.


I created a Windows Forms Application with a Windows Form containing a ComboBox.

                                                           enter image description here

I created a Local Database containing a Table with a single column and three test rows.

                                                             enter image description here

I added a data source containing the column I am interested in.

  enter image description here

Finally, I bound the combo box to the data source, but the result is strange.

                   enter image description here


Solution

  • This is the raw code to accomplish what you are asking:

    string strCmd = "";
    string strConn = "";
    SqlConnection sqlConn = new SqlConnection();
    SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn);
    SqlDataReader sqlRdr = new SqlDataReader();
    
    sqlConn.Open();
    
    if (comboBox1.Items.Count > 0)
       comboBox1.Items.Clear();
    sqlRdr = sqlCmd.ExecuteReader();
    
    while (sqlRdr.Read())
       comboBox1.Items.Add(sqlRdr[0].ToString());
    
    sqlRdr.Close();
    sqlConn.Close();
    

    There are a few things you will need to wire-up first though. The first one is this:

    string strCmd = "";  // Insert your SQL statement here.
    

    Second:

    string strConn = "";  // Your db connection string goes here.
    

    Thirdly:

    if (comboBox1.Items.Count > 0)  // You don't have to use this. It just checks to see 
       comboBox1.Items.Clear();     // if there is anything in the combobox and clears it.
    

    Lastly, since you are making something that handles interactions between your form and a database, I strongly suggest that you use SqlParameters to prevent SQL Injection attacks.