Friday, 30 January 2015

Show Bind Data to Asp.net Dropdownlist from Database in C#

   Show Bind Data to Asp.net Dropdownlist from Database in C#

Before implement this example first design one table UserInformation in your database as shown below

Column Name
Data Type
Allow Nulls
UserId
Int (set Identity=true)
No
UserName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database write the following code in your aspx page

<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>

Now add the following namespaces in code behind
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindContrydropdown();
}
}
/// Bind COuntrydropdown


protected void BindContrydropdown()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "UserName";
ddlCountry.DataValueField = "UserId";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("--Select--""0"));
con.Close();
}
}



No comments:

Post a Comment

thanks......

Bhabani Facebook