AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Wednesday, 28 October 2015

Bind Drop Down in ASP.NET

Binding Drop Down in ASP.NET is very easy. Here I am giving you example how to bind drop down list dynamically.


Method 1
Dynamically bind drop down from database.
SqlConnection conn;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Your_Connection_String"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from countries", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt=ds.Tables[0];
ddlCountry.DataSource = dt;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryId";
ddlCountry.DataBind();
If you want option select is also render in Drop Down list then use this code.
ddlCountry.AppendDataBoundItems = true;
ddlCountry.DataSource = dt;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryId";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, (new ListItem() { Value = "0", Text = "Select All" }));

Method 2
 you can also bind drop down list by Sql data Source. Open your aspx file & add new drop down list then select new Sql Data Source. Configure your sql data source & bind its properties DataTextField & DataValueField. Here I am giving you code example.
 <asp:dropdownlist id="DropDownList1" runat="server" datasourceid="SqlDataSource1" datatextfield="CountryName" datavaluefield="CountryID">   
   <asp:listitem> --Select--</asp:listitem>   
 </asp:dropdownlist>     
 <asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:your_connection_String %>" selectcommand="SELECT [CountryID],[CountryName] FROM Countries"></asp:sqldatasource>  

0 comments :

Post a Comment

  • Popular Posts
  • Comments