使用asp.net Web表单将值设置为空时验证下拉列表 [英] Validate dropdown when value is set to empty using asp.net web form

查看:25
本文介绍了使用asp.net Web表单将值设置为空时验证下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  <asp:DropDownList runat="server" ID="ddl">
    <asp:ListItem Text="-Select-" Value=""></asp:ListItem>
    <asp:ListItem Text="One" Value="1"></asp:ListItem>
    <asp:ListItem Text="Two" Value="2"></asp:ListItem>
    <asp:ListItem Text="Three" Value="3"></asp:ListItem>
  </asp:DropDownList>

<asp:CompareValidator ID="cvddl" runat="server" Text="Error" 
ControlToValidate="ddl" Operator="NotEqual" ValueToCompare = ""
ValidationGroup="CreateRolls"></asp:CompareValidator>

我确实想验证下拉列表,如果 select 被选中,应该抛出错误.主要目的是该值应该为空.

I do want to validate dropdown, if select is selected error should be thrown. Main aim is that the value should be empty.

有没有什么方法可以像这样验证.请帮我解决这个问题

Is there is any methord to validate like this . Please help me with this

推荐答案

已编辑答案的 Amarnath Balasubramanian(我无权添加评论)

Edited answer's Amarnath Balasubramanian (I have not permissions to add comments)

下拉列表

<asp:DropDownList ID="ddl" runat="server"
                  ValidationGroup="CreateRolls"
                  AppendDataBoundItems="true">
  <asp:ListItem Text="-Select-" Value="-1"></asp:ListItem>
  <asp:ListItem Text="One" Value="1"></asp:ListItem>
  <asp:ListItem Text="Two" Value="2"></asp:ListItem>
  <asp:ListItem Text="Three" Value="3"></asp:ListItem>
</asp:DropDownList>

RequiredFieldValidator

<asp:RequiredFieldValidator ID="rfvDDL" runat="server"
                            ControlToValidate="ddl" 
                            Display="Dynamic"
                            ErrorMessage="Values is required."
                            InitialValue="-1"
                            ForeColor="Red"
                            ValidationGroup="CreateRolls" >
</asp:RequiredFieldValidator>

代码中需要注意的重要属性如下

The Important property to be noted in the code is the following

ControlToValidate="ddl" 
InitialValue="-Select-"
ValidationGroup="CreateRolls"

注意变化是

<asp:ListItem Text="-Select-" Value="-1"></asp:ListItem>
InitialValue="-1"

这篇关于使用asp.net Web表单将值设置为空时验证下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆