Wednesday, June 13, 2012

Binding data to ComboBox in C# Windows Form


In this post Binding data to ComboBox in C# Windows Form, we shall see on how to query data from a SQL Server database and bind the results to a ComboBox control.

First let us create a new Windows form and add a ComboBox control to the form.
Once we are done we can navigate to the code view and add the code to get data from SQL Server and bind the same to the ComboBox.

Since we are going to get the data from SQL Server database, add a reference to
using System.Data.SqlClient;

Add the following code to form Load event, to load the ComboBox with data.

private void frmViewEmployees_Load(object sender, EventArgs e)
{
    BindDepartments();
}
//
private void BindDepartments()
{
    // Read the connection string from the app.config file.
    string strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
    SqlConnection objConn = new SqlConnection(strConn);
    SqlCommand objCmd = new SqlCommand("SELECT 0 as ID,'-Select-' as Name UNION SELECT ID, NAME FROM DEPARTMENT", objConn);
    SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
    DataSet dsDepartment = new DataSet();
    //
    objDA.Fill(dsDepartment, "dtDepartment");
    //
    cmbDepartment.DataSource = dsDepartment.Tables["dtDepartment"];
    cmbDepartment.DisplayMember = "Name";
    cmbDepartment.ValueMember = "ID";
}

Run the application,  the form opens up with the ComboBox populated with data from the SQL Server database.

That’s it we have populated a ComboBox, with data from a SQL Server database using C# Windows forms.

Search Flipkart Products:
Flipkart.com

3 comments: