Thursday, 16 May 2013

Bind dropdownlist in asp.net


Bind dropdownlist in asp.net



Once table designed in database write the following code in your aspx page
source code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to show data in dropdownlist from database in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlCountry" runat="server" />
</div>
</form>
</body>
</html>


C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
    BindDatadropdown();
}
}
protected void BindDatadropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection("your connetion string")
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select UserId,UserName FROM UserTable", con);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "UserName";
ddlCountry.DataValueField = "UserId";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0,"Select");
con.Close();
}
}

No comments:

Post a Comment