Wednesday, 5 June 2013

How to fill DropDownList from Sql server database in

How to fill DropDownList from Sql server database in

Introduction: In previous article i explained how to Fill CheckBoxList based on DropDownList selection in, VB) and How to open Pop up window on Drop down selection in  and How to fill dropdownlist with days, month and year in, VB) .One of the common requirement while working on application is to dynamically Fill/Bind DropDownList from Sql server table. Suppose we want to fillDropDownList on page load from department table then here is the way:

Bind DropDownList example  in
  • Create a table in the Sql server database as shown in Figure and name it DEPARTMENT_TABLE

Bind DropDownList example  in

  • Place a DropDownList control on your design page (.aspx) of website.
<asp:DropDownList ID="ddlDept" runat="server">
  • Create function in the code behind file to Fill/Bind DropDownList  and call it on  Page load event:
C#.NET Code
    protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
protected void FillDeptDropdownList()
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbCon"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from DEPARTMENT_TABLE", con);
        SqlDataAdapter adp=new SqlDataAdapter(cmd);
        DataTable dt=new DataTable();
        ddlDept.Items.Insert(0,"Select Department");
       //OR    ddlDept.Items.Insert(0, new ListItem("Select Department", "-1"));       

No comments:

Post a Comment