如何将 RequiredFieldValidator 添加到 DropDownList 控件?
我有一个 DropDownList
绑定了一个 SqlDataSource
来显示数据库中的值.
I have a DropDownList
binded with aSqlDataSource
to display the values from the database.
我无法使用 RequiredFieldValidator
进行验证.
I am unable to validate using a RequiredFieldValidator
.
在大多数情况下,您将其视为验证任何其他类型的控件,但使用所需字段验证器的 InitialValue 属性.
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" />
基本上它的意思是,如果在下拉列表中选择了除 InitialValue 中设置的 1 之外的任何其他值,则验证将成功.
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");