I have a dropdownlist which I am developing dynamically in the code.
Dim objPreferenceDropdownList As DropDownList = New DropDownList()
objPreferenceDropdownList.ID = "objPreferenceDropdownList"
objPreferenceDropdownList.AppendDataBoundItems = "True"
objPreferenceDropdownList.AutoPostBack = True
I am populating this dropdown with different items such as
objPreferenceDropdownList.Items.Add(new ListItem("--Select Color--","0"));
objPreferenceDropdownList.Items.Add(new ListItem("Red","1"));
objPreferenceDropdownList.Items.Add(new ListItem("Blue","2"));
objPreferenceDropdownList.Items.Add(new ListItem("White", "3"));
objPreferenceDropdownList.Items.Add(new ListItem("Pink", "4"));
Now I need to validate the dropdownlist it there is no any item selected in the dropdown for that I created a required field validator dynamically like this:
Dim reqPrefGroupValidator As RequiredFieldValidator = New RequiredFieldValidator()
reqPrefGroupValidator.ControlToValidate = "objPreferenceDropdownList"
reqPrefGroupValidator.InitialValue = "0"
reqPrefGroupValidator.SetFocusOnError = True
prefdiv.Controls.Add(reqPrefGroupValidator)
The problem is required field validator only works when dropdownlist is empty what if I need to fire requiredfieldvalidator when the selected item value of dropdownlist is zero.
Set the InitialValue of the validator to 0 and the validator must have and ID ofcourse as:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="objPreferenceDropdownList"
InitialValue="0"></asp:RequiredFieldValidator>