We use RequiredFieldValidator control to make a field mandatory in ASP.Net. This little tip will help us to use a DropDownList control with RequiredFieldValidator control. This code snippet will insert a default item as the first Item to the DropDownList with value as empty. In this scenario, When a RequiredFieldValidator is associated with DropDownList through its ControlToValidate property; it will make the DropDownList as a mandatory field when it is left with default value selection.
ASPX
<asp:DropDownList ID="ddlRank" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlRank"
ErrorMessage="Select a Rank"></asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" />
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlRank.Items.Add(new ListItem("Select",""));
ddlRank.Items.Add(new ListItem("1", "1"));
ddlRank.Items.Add(new ListItem("2", "2"));
ddlRank.Items.Add(new ListItem("3", "3"));
}
}
Execute the page. You will receive an error message when you click Save without selecting a value in DropDownList control.
|