tabs

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="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <b>Selected UserName:</b>
            <asp:DropDownList ID="ddlCountry" runat="server" />
        </div>
    </form>
</body>
</html>


 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"))
        {
           cn.Open();
           SqlCommand cmd = new SqlCommand("Select UserId,Location FROM Contacts",cn);
           SqlDataAdapter da = new SqlDataAdapter(cmd);
           DataSet ds = new DataSet();
           da.Fill(ds);
           ddlLocation.DataSource = ds;
           ddlLocation.DataTextField = "Location";
           ddlLocation.DataValueField = "UserId";
           ddlLocation.DataBind();
           ddlLocation.Items.Insert(0, new ListItem("—Select Location--""0"));
           cn.Close();
        }
    }

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