尝试在ASP.NET中以编程方式设置RangeValidator的Max和Min值

时间:2016-11-06 17:55:08

标签: asp.net

我试图以编程方式设置RangeValidator的Max和Min值,如下所示:

<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RangeValidator" 
MaximumValue="<%# Max %>" MinimumValue="<%# Min %>" Type="Integer" > 
Value should be in <%# Min %> and <%# Max %> </asp:RangeValidator>

这里,Min和Max是代码隐藏的整数。但是得到错误: “'RangeValidator1'的MaximumValue属性的值''无法转换为'Integer'类型。” 我真的很感谢这方面的任何帮助。感谢

2 个答案:

答案 0 :(得分:0)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" >
 <asp:RangeValidator ID="RangeValidator1" runat="server"ErrorMessage="RangeValidator"></asp:RangeValidator>
    </form>
</body>
</html>

Codebehind代码

 protected void Page_Load(object sender, EventArgs e)
        {
            RangeValidator1.MinimumValue = 1.ToString();
            RangeValidator1.MaximumValue = 5.ToString();
        }

上面的代码可以帮助您实现目标。

答案 1 :(得分:0)

以下是RangeValidator的完整语法。

<asp:RangeValidator 
         id="ProgrammaticID" 
         ControlToValidate="ProgrammaticID of control to validate" 
         MinimumValue="value"
         MaximumValue="value" 
         Type="DataType" 
         ErrorMessage="Message to display in ValidationSummary control"
         Text="Message to display in control"
         ForeColor="value" 
         BackColor="value"  
         runat="server" >
    </asp:RangeValidator>

注意如果MaximumValue或MinimumValue属性指定的值无法转换为Type属性指定的数据类型,则RangeValidator控件将引发异常。 MSDN Source

因此,请尝试正确设置 Type 属性,或将 Max Min 值更改为适当的类型。在您的情况下,尝试将 Min Max 转换为Integer。