Binding a combo box is nothing but, how to get the data from SQL to combo box. Follow the below steps to bind the data from the database.
Step 1
Drag and drop the combo box control onto the form.
Step 2
Give the appropriate Name for the combo box control.
Step 3
Double click on the form. Then the coding form (Form1.cs) will be open.
Step 4
Add the following namespaces in the namespaces section.
[csharp]
using System.Data;//provides different classes that access ADO.net architecture
using System.Data.SqlClient;//contains collection of classes to access sql server
[/csharp]
Alternative
forms
There are two ways to bind combo box control
Under the Form_Load.
Under the combo box SelectedIndexChanged event.
If you want to bind the combo box at the starting that means while the form has been loading, then simply write the below code under the Form_Load event.
If you want to bind the combo box when the user changes the index or selecting the item. Then simply write the below code under the SelectedIndexChanged event.
[csharp]
private void ComboBoxBinding_Load(object sender, EventArgs e)
{
//creates an object for connection class and provides connection to database
SqlConnection con = new SqlConnection("Data Source=IQUICK/MSSQL;Initial Catalog=Sample;Persist Security Info=True;User ID=sa;Password=123");
//The command or query which we want to give
SqlCommand cmd = new SqlCommand("Select * from tbl_emp",con);
//creates an object for adapter and executes the command object
SqlDataAdapter da = new SqlDataAdapter(cmd);
//creates an object for dataset
DataSet ds = new DataSet();
//fills the table in the dataset
da.Fill(ds);
//The table which we want to use
cmbCity.DataSource = ds.Tables[0];
//The field which we want to bind to the combo box
cmbCity.DisplayMember = "City";
//used for referring the field
cmbCity.ValueMember = "Id";
}
[/csharp]