Introduction
In this quick article you will learn how to bind the data to a DropDownList and ListBox controls in ASP.NET. I know this is very easy but today a novice ASP.NET guy who is my friend on Facebook asked me about this and I created this solution for him.
Look at the animated image that we are going to create in this article.

Binding Data to DropDownList Control
To bind the data to DDL, just place the DDL Control on your web page and write the C# logic in code-behind.
Default.aspx Code
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
</asp:DropDownList>
</div>
C# Code
DropDownList1.Items.Add(new ListItem("Select Customer", ""));
DropDownList1.AppendDataBoundItems = true;
String strConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
String strQuery = "SELECT CustomerID, ContactName FROM Customers";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "ContactName";
DropDownList1.DataValueField = "CustomerID";
DropDownList1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
Binding Data to ListBox Control
To bind the data to the LB, just place the LB Control on your web page and write the C# logic in code-behind.
Default2.aspx
<div>
<asp:ListBox ID="ListBox1" runat="server">
</asp:ListBox>
</div>
Default2.aspx.cs
ListBox1.Items.Add(new ListItem("Select Customer", ""));
ListBox1.AppendDataBoundItems = true;
String strConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
String strQuery = "SELECT CustomerID, ContactName FROM Customers";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "ContactName";
ListBox1.DataValueField = "CustomerID";
ListBox1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to execute some business logic when the user selects the item from a DropDownList, you just need to add another method and call it from the DropDownList's OnSelectedIndexChanged. Find the code below:
Defaulat.aspx

Join the conversation! Your thoughts help the community grow.