如何在下拉列表中创建必填字段验证器?

时间:2014-03-19 09:55:57

标签: c# asp.net drop-down-menu requiredfieldvalidator

我有一个下拉列表,我在其中添加了一个额外的值(选择频道...)。如果选择此值,我想要显示所需的消息,我尝试的是:

<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="-1" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="-1"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

不幸的是,这只是让我选择初始值(数据库中自然不存在)而不说它是不允许的。怎么解决这个问题?

3 个答案:

答案 0 :(得分:2)

你需要在你的代码中添加默认值(.cs)来绑定Dropdownlist数据,而不是在.aspx页面中进行。

ServiceChannelDropDownList.DataBind();
ServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));

答案 1 :(得分:1)

<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="0" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="0"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

答案 2 :(得分:0)

我需要将ValidationGroup添加到RequiredFieldValidator,例如

<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                            ControlToValidate="ServiceChannelDropDownList"
                            InitialValue="0"
                            ErrorMessage="Channel is required."
                            ValidationGroup="WorkflowValidation" 
                            CssClass="ValidationCss" 
                            EnableTheming="false">*
                        </asp:RequiredFieldValidator>

谢谢大家的帮助!