Bind ComboBox In Windows Application Using C#

In this article, I will show you how to bind ComboBox with database in Windows Application using C#.

We make one table and bind that data to our ComboBox.

Initial chamber

Step 1: Open Your Visual Studio 2010, Go to File, New, Projects and under Visual C#, go to Windows.

windows form application

You can change the name of the project and  browse your project to different location too. And then press OK.

Step 2: In Solution Explorer you get your Project, Add Service Based Database. By going to your Project, Right Click and Add New Item, then Service Based Database.

service based database

Database chamber

Step 3: Get to your Database [Database.mdf], we will create a table tbl_Data. Go to the database.mdf, Table and Add New table. Design your table like this following:

Tbl_data:

table design

Show tbl_data:

table

Design chamber


Step 4: Now open your Form1.cs[Design] file, where we create our design for ComboBox Binding.

We will drag ComboBox from the tool box to Form1.cs [Design], you will see your Form look like the following:

ComboBox

Code chamber

Right Click on the blank part of Form1.cs, then View Code. You will see you entered in the code part of the form. Write the following code and then press F5 to run the project.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data.SqlClient;  
  10.   
  11. namespace WindowsFormsApplication1  
  12. {  
  13.     public partial class Form1 : Form  
  14.     {  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.             refreshdata();  
  19.         }  
  20.         public void refreshdata()     
  21.         {  
  22.             DataRow dr;  
  23.   
  24.   
  25.             SqlConnection con = new SqlConnection(@"Data Source=NiluNilesh;Initial Catalog=mynewdata;Integrated Security=True");  
  26.             con.Open();  
  27.             SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  28.             SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  29.             DataTable dt = new DataTable();  
  30.             sda.Fill(dt);  
  31.   
  32.             dr = dt.NewRow();  
  33.             dr.ItemArray = new object[] { 0, "--Select Movie--" };  
  34.             dt.Rows.InsertAt(dr, 0);  
  35.              
  36.             comboBox1.ValueMember = "id";  
  37.           
  38.             comboBox1.DisplayMember = "movie";  
  39.             comboBox1.DataSource = dt;  
  40.               
  41.             con.Close();    
  42.         }           
  43.     }       
  44. }  
Output chamber

Output

Hope you like this. Thank you for reading. Have a good day.