gpt4 book ai didi

带有 DropDownList 的 ASP.Net 自定义验证器控件

转载 作者:行者123 更新时间:2023-12-02 21:22:38 25 4
gpt4 key购买 nike

以下代码用于使用自定义验证器验证 DropDownList 控件。

默认1.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>

默认1.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.

关于带有 DropDownList 的 ASP.Net 自定义验证器控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com