Hi,
Many of the people new to ASP.Net would be excited about the Dropdownlist control which is very useful in appliactions. Howevever, much as it is easy to add items to the dropdownlist with static asp:ListItem tags, adding values to the dropdownlist dynamically is a bit complex and involves a little bit of coding.
Also, one of the common issues faced by developers is how to enforce Required Field Validator for Dropdownlist.
Herebelow is the code snippet for a Dropdownlist with validator and dynamically filling the same from Database. It uses an imaginary table tblCountry which has the fields CountryId, CountryName. The select statement is pretty straightforward and can be tweaked accordingly to one's requirement.
ASPX Code for declaring the control with Required Field Validator
===================================================================
asp:dropdownlist id="ddlCountry" runat="server" DataTextField="CountryName" DataValueField="CountryId"
asp:requiredfieldvalidator id="CountryValidator" Runat="server" ControlToValidate="ddlCountry"
ErrorMessage="Please select your Country" InitialValue="0"
C# Code for populating the dropdownlist dynamically from the database
=====================================================================
public void Bind_ddlCountry()
{
SqlConnection objcon = new SqlConnection("Connectionstring");
SqlCommand objcmd;
SqlDataReader objRdr;
string selstr;
selstr = "SELECT CountryId, CountryName FROM tblCountry";
objCmd = new SqlCommand(selstr, objCon);
try
{
objCon.Open();
objRdr = objCmd.ExecuteReader();
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("CountryName", typeof(string)));
dt.Columns.Add(new DataColumn("CountryId", typeof(string)));
dr = dt.NewRow();
dr["CountryName"] = "Choose One";
dr["CountryId"] = 0;
dt.Rows.Add(dr);
while(objRdr.Read())
{
dr = dt.NewRow();
dr["CountryName"] = objRdr["CountryName"];
dr["CountryId"] = objRdr["CountryId"];
dt.Rows.Add(dr);
}
ddlCountry.DataSource = dt;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryId";
ddlCountry.DataBind();
objRdr.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
objCon.Close();
objCon.Dispose();
objCmd.Dispose();
}
}
Hope it helps.