Tuesday, November 12, 2013

Bind a DropdownList with Database Values

"In this post I am going to explain you how to bind the drop-down list items with the values present in your database table".
Generally for static pages we add the drop-down list items manually. But what if the application is dynamic. We need to fetch the dropdown list items from the database accordingly.
So here i am going to explain how to bind the drop-down list with database values with a simple example
First create a table with name as Contacts in your database as below:

‘UserId’ should be the primary key and set its column property ‘Identity Specification’ to yes.
The following should be the code in your .aspx page:

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            <b>Selected UserName:</b>
            <asp:DropDownList ID="ddlCountry" runat="server" />

 And here is the code behind:

   protected void BindLocation()
        using (SqlConnection cn = new SqlConnection("Data Source=localhost;
              Integrated Security=true;Initial Catalog=Your Database Name"))
           SqlCommand cmd = new SqlCommand("Select UserId,Location FROM Contacts",cn);
           SqlDataAdapter da = new SqlDataAdapter(cmd);
           DataSet ds = new DataSet();
           ddlLocation.DataSource = ds;
           ddlLocation.DataTextField = "Location";
           ddlLocation.DataValueField = "UserId";
           ddlLocation.Items.Insert(0, new ListItem("—Select Location--""0"));

That’s all. Your location from the database gets bound to the location dropdown list of your web page. This is how you bind a dropdown list with database values.
Hope it helps you and feel free to post and suggest me with your valuable comments.

No comments:

Post a Comment