I have a DropDownList
binded with aSqlDataSource
to display the values from the database.
I am unable to validate using a RequiredFieldValidator
.
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
Suppose your Drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
You have two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0"....
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToComare="0" ConroltoCompare="ddl" Operator="Equel"....
If you are using a data source, here's another way to do it without code behind.
Note the following key points:
- The
ListItem
ofValue="0"
is on the source page, not added in code - The
ListItem
in the source will be overwritten if you don't includeAppendDataBoundItems="true"
in theDropDownList
InitialValue="0"
tells the validator that this is the value that should fire that validator (as pointed out in other answers)
Example:
<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType"
InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server"
ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>
InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.
<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />
来源:https://stackoverflow.com/questions/2280559/how-to-add-a-requiredfieldvalidator-to-dropdownlist-control