Data Binding to DropDownList and ListBox in ASP.NET

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.

image1.gif
 

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

        <div>
            Select Customer ID
               
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
                    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                </asp:DropDownList>
            <br /><br /><br />
            <hr />
            <br />
                Company Name: <asp:TextBox ID="txtCompanyName" runat="server"></asp:TextBox>
            <br />
                Contact Title: <asp:TextBox ID="txtContactTitle" runat="server"></asp:TextBox>
            <br />
                Address: <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
            <br />
                City: <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
            <br />
                Country: <asp:Label ID="lblCountry" runat="server" Text=""></asp:Label>
            <br />

        </div>

Default.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
       
if (!IsPostBack)
        {
            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();
            }
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
       
String strConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
       
String strQuery = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
       
SqlConnection con = new SqlConnection(strConnString);
       
SqlCommand cmd = new SqlCommand();
        cmd.Parameters.AddWithValue(
"@CustomerID", DropDownList1.SelectedItem.Value);
        cmd.CommandType =
CommandType.Text;
        cmd.CommandText = strQuery;
        cmd.Connection = con;
       
try
        {
            con.Open();
           
SqlDataReader sdr = cmd.ExecuteReader();
           
while (sdr.Read())
            {
                txtCompanyName.Text = sdr[
"CompanyName"].ToString();
                txtContactTitle.Text = sdr[
"ContactTitle"].ToString();
                txtAddress.Text = sdr[
"Address"].ToString();
                txtCity.Text = sdr[
"City"].ToString();
                lblCountry.Text = sdr[
"Country"].ToString();
            }
        }
       
catch (Exception ex)
        {
           
throw ex;
        }
       
finally
        {
            con.Close();
            con.Dispose();
        }
    }

I hope you like it. Thanks. Happy Coding!