Data Binding to DropDownList and ListBox in ASP.NET

Introduction

In this quick post you are going to learn how to bind the data to 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 this to me and I created this solution for him.

Look at the animated image that we are going to create in this post.


Binding Data to DropDownList Control

To bind the data to DDL, just place the DDL Control on your web page and write the C# logics 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 LB, just place the LB Control on your web page and write the C# logics 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 logics when user selects the item from DropDownList, you just need to add another method and call it from 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!!

Comments

  1. Hi, it's a great post,The concept of data binding makes it easy to associate and bind the data in the application screen to the file it is persisted in.

    ReplyDelete
  2. i want this solution in VB code in asp.net....
    rly soon.

    ReplyDelete
  3. how to trasnfer data from drop down to list box

    ReplyDelete
    Replies
    1. from above ...file Default2.aspx.cs for add value to list box
      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();
      }

      Delete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System