Populate Combobox with Data Stored in SQL Server 2008 using C#

In this tutorial, I will teach you how to create a program that will load records to a combobox from a SQL Server 2008 database using c#. This will be very helpful in making your systems or thesis. So, now let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application. 2. Add only one combobox in your Form. design 3. We will first create a database named populateCombo using the SQL Server 2008 database. Create a table named tblNames and have an entity of StudentName with a varchar datatype. design Then put records inside the table and we will retrieve this later in our combobox. design 4. Now, let's do the coding. We will first import the SQL namespace as we will have the SQL database.
  1. using System.Data.SqlClient;
Have the connection string of your sql database, the command, connection, and the data reader.
  1. public SqlCommand cm = new SqlCommand();
  2. public SqlConnection cn = new SqlConnection();
  3. public SqlDataReader dr;
  4.  
  5. public string constring = @"Data Source=don-PC;Initial Catalog=populateCombo;Integrated Security=True"
Create a function named loadNames() that will load the records from the database to the combobox. Use the table named tblNames.
  1. void loadNames()
  2. {
  3. string sql = "Select * from tblNames";
  4. cm = new SqlCommand(sql, cn);
  5. dr = cm.ExecuteReader();
  6. while (dr.Read())
  7. {
  8. //call the first column of the records inside the tblNames
  9. comboBox1.Items.Add(dr.GetValue(0).ToString());
  10. }
  11. dr.Close();
  12. }
And then call this loadNames() function inside the Form_Load with the connection of your database to open it. .
  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3. cn = new SqlConnection(constring);
  4. cn.Open();
  5. loadNames();
  6. }
Output: output For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment