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.
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;
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.
3 comments:
Hi also try this..http://codingresolved.com/discussion/58/how-to-fill-combobox-from-database-in-c-sharpc
good article ..keep it up..also visit my site www.mobilemart.pk
C# ComboBox Control
Post a Comment