我想在代碼後面的文件中使用必需的字段驗證程序,但它顯示以下錯誤。C#代碼中所需的字段驗證程序#
錯誤:
Unable to find control id 'TextBox1' referenced by the 'ControlToValidate' property of 'abcd854'
注:TextBox1的頁面存在。我已經測試過它。
ASPX頁面
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="save" />
</p>
<p>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</asp:Content>
銫文件
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//RequiredFieldValidator validator = ControlsValidation.AssignRequiredFieldValidatorToControl(TextBox1, "Field is required", "*", "save");
//validator.ControlToValidate = ((TextBox)this.Form.FindControl("MainContent").FindControl("TextBox1")).ID;
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.ID = "abcd" + new Random().Next(100, 1000);
validator.ControlToValidate = ((TextBox)this.Form.FindControl("MainContent").FindControl("TextBox1")).ID;
validator.EnableClientScript = true;
validator.ErrorMessage = "";
validator.Text = "*";
validator.ValidationGroup = "save";
validator.Display = ValidatorDisplay.Dynamic;
this.Controls.Add(validator);
}
}
代碼嘗試設置文本框的ID模式,靜態 – qamar
沒有工作。運氣不好 –
當你找到控件時((TextBox)this.Form.FindControl(「MainContent」)。FindControl(「TextBox1」)); – qamar