Add a Default List Item to DropDownList When Binding from DataBase in Asp.Net
We always set the first item of an ASP.Net DropDownList as "Select" to let the user know to select a value. From ASP.Net 2.0, all list controls (CheckBoxList, DropDownList, ListBox, and RadioButtonList) includes a new Boolean property called AppendDataBoundItems which can be used to achieve this task very easily. Add a default ListItem in ASPX and bind the DropDownList from database like below,
ASPX <asp:DropDownList ID="ddlDepartment" AppendDataBoundItems="true" runat="server"> <asp:ListItem Text="Select" Value=""></asp:ListItem> </asp:DropDownList>
CodeBehind protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dtDept = GetDept(); ddlDepartment.DataSource = dtDept; ddlDepartment.DataTextField = "Department"; ddlDepartment.DataValueField = "DeptID"; ddlDepartment.DataBind(); } }
public DataTable GetDept() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); con.Open(); SqlCommand com = new SqlCommand("SELECT * FROM [Department]", con); SqlDataAdapter ada = new SqlDataAdapter(com); DataSet ds = new DataSet(); ada.Fill(ds); return ds.Tables[0]; }
When the above code is executed, the DropDownList will have "Select" as first item and the other items from database will be appended. Refer the below output,
OUTPUT <select name="ddlDepartment" id="ddlDepartment"> <option value="">Select</option> <option value="1">IT</option> <option value="2">CSE</option> <option value="3">SALES</option> <option value="4">HR</option> <option value="5">PROD</option> </select>
|