WebForms页面中的RangeValidator失败,出现错误

时间:2018-09-27 16:11:24

标签: webforms rangevalidator

我的任务是维护旧的Webforms应用程序,而无需太多的培训或经验。

有人要求我向现有表中添加一个新字段,并将其显示在网页中。这是执行此操作的代码,我以其他现有字段和代码为模型。

 <asp:TextBox ID="PortableBarrelCompressionValuetextBox" 
    runat="server" 
    SkinID="FVTextBox" 
    Text='<%# Bind("PortableBarrelCompressionValue") %>'  
    <asp:RangeValidator 
    ID="RangeValidatorPortableBarrelCompressionValuetextBox"
    runat="server" 
    ControlToValidate="PortableBarrelCompressionValuetextBox"
    CssClass="failureNotification" 
    Display="Dynamic"
    ErrorMessage="Whole Numbers Between 0 and 9999" 
    MaximumValue="9999"
    MinimumValue="0"
    Type="Integer" 
    Text='<%# Eval("PortableBarrelCompressionValue") %>'>
    </asp:RangeValidator>

仅当现有值不为空(当然,在范围内)时,此方法才能正确运行。如果我将有效数字(例如22)更改为其他有效数字(200),则会按预期保存更改。

但是,如果现有记录上的值为null,而我尝试添加一个整数,它将失败并显示错误消息:

Value   {" is not a valid value for Int32."}    System.Exception

如果存在一个已删除的有效值,并且出现相同的错误,也会失败。

此字段不是必填字段,因此我必须在此处保留Null。

在过去的两天内,我已经学到了足够的知识来确定这种情况的发生,因为该字段是整数,并且Null不能转换为用于验证的字符串(至少这就是我现在所假设的)

如果这是真的,那就是问题,我需要找到一种解决方法。

我在正确的轨道上吗?

是否有一种方法可以提供验证,该验证除了在适当范围内的整数之外,还将在此字段中接受空值?

谢谢。

2 个答案:

答案 0 :(得分:0)

这不会引发您的错误

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="FredWebForm.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <%--bind only used with controls that have datasource eg grid--%>
    <asp:TextBox runat="server" Text='<%# GetStatus("PortableBarrelCompressionValue") %>' ID="MyTextBox" />
    <asp:RangeValidator
        ID="RangeValidatorPortableBarrelCompressionValuetextBox"
        runat="server"
        ControlToValidate="MyTextBox"
        CssClass="failureNotification"
        Display="Dynamic"
        ErrorMessage="Whole Numbers Between 0 and 9999"
        MaximumValue="9999"
        MinimumValue="0"
        Type="Integer"
        Text='Needs to be a number between 0 and 9999'>
    </asp:RangeValidator>
</asp:Content>

后面的代码

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataBind();
        }
    }

    protected string GetStatus(string theID)
    {
        return null;
    }
}

答案 1 :(得分:0)

我终于发现了我的错误。

它根本不在本节中。

我没有意识到表单的LingDataSource定义也必须更新。

一旦我添加以下行:

<asp:Parameter Name="PortableBarrelCompressionValue"
ConvertEmptyStringToNull="true" />

它复活了。

感谢所有支持。

相关问题