Required Field Validator in code behind C#

shujaat siddiqui picture shujaat siddiqui · Dec 27, 2014 · Viewed 19.8k times · Source

I am trying to use required field validator in code behind file but it is showing the following error.

Error:

Unable to find control id 'TextBox1' referenced by the 'ControlToValidate' property of 'abcd854'

Note: TextBox1 exists in the page; I have tested it.

enter image description here

Aspx Page

  <%@ 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>
        &nbsp;<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</asp:Content>

Cs File

   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);
        }
    }

Answer

shujaat siddiqui picture shujaat siddiqui · Dec 27, 2014

The issue was:

 this.Controls.Add(validator);

As we all can see, TextBox1 is in child page, meaning "Content Page", so when using the above line of code, it adds the control in the master page, in which there is no control with the id "TextBox1".

After replacing the above line of code with:

this.Form.FindControl("MainContent").Controls.Add(validator);

it's working perfectly.