加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

使用DropDownList的ASP.Net自定义验证器控件

发布时间:2020-12-16 07:24:37 所属栏目:asp.Net 来源:网络整理
导读:以下代码用于使用Custom Validator验证DropDownList控件. Default1.aspx td asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px" asp:ListItemSelect/asp:ListItem asp:ListItemNokia/asp:ListItem asp:ListItemLG/asp:ListItem
以下代码用于使用Custom Validator验证DropDownList控件.

Default1.aspx

<td>
        <asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px">
             <asp:ListItem>Select</asp:ListItem>
             <asp:ListItem>Nokia</asp:ListItem>
             <asp:ListItem>LG</asp:ListItem>
             <asp:ListItem>Samsung</asp:ListItem>
             <asp:ListItem>sony</asp:ListItem>
             <asp:ListItem>Micromax</asp:ListItem>
             <asp:ListItem>Karbonn</asp:ListItem>
             <asp:ListItem>Apple</asp:ListItem>
         </asp:DropDownList>
    </td>
    <td>
         <asp:CustomValidator ID="cv1" Display="Dynamic" ControlToValidate = "DDL_Product" OnServerValidate="ddl_server" runat="server" ForeColor="Red" ErrorMessage="Please Select the Product"></asp:CustomValidator>
    </td>

Default1.aspx.cs

protected void ddl_server(object sender,ServerValidateEventArgs e)
{
     if (e.Value.selectedIndex <= 0)
     {
        e.IsValid = true;
     }
     else
     {
        e.IsValid = false;
     }
}

以上验证未经验证.
我不知道如何使用此控件并验证DropDownList.请更正错误.

解决方法

你应该使用RequireValidator.

1)添加“选择”项的值,将用于验证初始值:

<asp:DropDownList ID="DDL_Product" runat="server" Height="21px" Width="128px">
       <asp:ListItem Value="0">Select</asp:ListItem>
       /*Rest of items*/
</asp:DropDownList>

2)然后像这样使用RequireValidator,比较DDL的初始值:

<asp:RequiredFieldValidator InitialValue="0" 
    ID="rfvDDL_Product" Display="Dynamic" 
    ControlToValidate="DDL_Product"
    runat="server"  Text="*" 
    ErrorMessage="Please Select the Product"
    ForeColor="Red">
</asp:RequiredFieldValidator>

编辑:

有关解释,请访问MSDN:

CustomValidator Class

Use the CustomValidator control to provide a user-defined validation
function for an input control. The CustomValidator control is a
separate control from the input control it validates,which allows you
to control where the validation message is displayed.

RequiredFieldValidator Class

Use this control to make an input control a required field. The input control fails validation if its value does not change from the InitialValue property upon losing focus.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读