Thursday, July 14, 2011

asp .net required field validation on dropdown list

First, in the code-behind, retrieve the DataSource of the dropdownlist but add a new item with "XXX" code and [Please select] name, somewhat like this:

List countries = EnumHelper.CountryList();
Country unselectedCountry = new Country { CountryCode = "XXX", CountryName = "[Please select]" };
countries.Insert(0, unselectedCountry);
ddCountry.DataSource = countries;

Then, create a RequiredFieldValidator in your aspx file with the following properties:

<asp:RequiredFieldValidator runat="server" ControlToValidate="ddCountry" Display="Dynamic" ErrorMessage="*" InitialValue="XXX" ToolTip="Required">
</asp:RequiredFieldValidator>

It will now validate if the dropdown list has no selected index yet because of the added code.

Happy coding!

No comments: