Reputation: 1577
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.
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>
<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);
}
}
Upvotes: 4
Views: 23590
Reputation: 431
In ASP.NET, after rendering your page, the TextBox's id will be changed (see source code in browser). you can change its client id mode to static so that it won't change.
Add ClientIDMode="Static"
in your textbox
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
Upvotes: 1
Reputation: 1577
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.
Upvotes: 5
Reputation: 11
Try This...
Code behind
oTexbox1.Attributes["required"] = "true";
Upvotes: 1
Reputation: 1001
Try using ClientID instead of ID
RequiredFieldValidator validator = new RequiredFieldValidator();
validator.ID = "abcd" + new Random().Next(100, 1000);
validator.ControlToValidate = ((TextBox)this.Form
.FindControl("MainContent").FindControl("TextBox1")).ClientID;
validator.EnableClientScript = true;
validator.ErrorMessage = "";
validator.Text = "*";
validator.ValidationGroup = "save";
validator.Display = ValidatorDisplay.Dynamic;
this.Controls.Add(validator);
Upvotes: -2