Reputation:
I am adding controls to the page as well as the RequiredFieldValidator
controls, but something is going wrong.
int i = 4; // for testing; for now
// add surname textbox
PlaceHolderResidents.Controls.Add(new LiteralControl("<div class=\"control-group\">"));
TextBox tb1 = new TextBox();
tb1.ID = "LastName" + i;
tb1.CssClass = "input-xlarge";
labelLastName.AssociatedControlID = tb1.ID;
PlaceHolderResidents.Controls.Add(labelLastName);
PlaceHolderResidents.Controls.Add(new LiteralControl("<div class=\"controls\">"));
PlaceHolderResidents.Controls.Add(tb1);
RequiredFieldValidator rfv1 = new RequiredFieldValidator();
rfv1.ControlToValidate = tb1.ID; // ERROR HERE
rfv1.ErrorMessage = GetLocalResourceObject("RequiredFieldValidator_LastNameResource.ErrorMessage").ToString();
PlaceHolderResidents.Controls.Add(rfv1);
I am getting an error
System.Web.HttpException: Unable to find control id 'LastName4' referenced by the 'ControlToValidate' property of ''.
This code is placed in Page_Load()
, but I tried placing it in other Page
events without success. Any ideas? Thank you.
EDIT: Full code for this section.
PlaceHolderResidents.Controls.Add(new LiteralControl("\n\n<div class=\"control-group\">"));
Label labelLastName = new Label();
labelLastName.Text = GetLocalResourceObject("LastNameLabelResource.Text").ToString();
labelLastName.CssClass = "control-label asterisk";
TextBox tb1 = new TextBox();
tb1.ID = "LastName" + i;
tb1.CssClass = "input-xlarge";
labelLastName.AssociatedControlID = tb1.ID;
PlaceHolderResidents.Controls.Add(labelLastName);
PlaceHolderResidents.Controls.Add(new LiteralControl("\n<div class=\"controls\">"));
PlaceHolderResidents.Controls.Add(tb1);
PlaceHolderResidents.Controls.Add(new LiteralControl("\n<p class=\"help-block\">"));
RequiredFieldValidator rfv1 = new RequiredFieldValidator();
rfv1.ControlToValidate = tb1.ID;
rfv1.ErrorMessage = GetLocalResourceObject("RequiredFieldValidator_LastNameResource.ErrorMessage").ToString();
rfv1.EnableClientScript = false;
PlaceHolderResidents.Controls.Add(rfv1);
PlaceHolderResidents.Controls.Add(new LiteralControl("\n</p></div></div>"));
It is interesting to note that I have more of these validators on the page and most of them are working. If I comment out the code above many validators on the page work (there is one another RequiredFieldValidator
that gives the same error for some reason).
EDIT 2: The code above works. Not sure what was wrong.
Upvotes: 0
Views: 833
Reputation: 1449
As per my knowledge, you can't access that directly. You might have to use "FindControl()" method as shown below.
RequiredFieldValidator rfv1 = new RequiredFieldValidator();
rfv1.ControlToValidate = PlaceHolderResidents.FindControl(tb1.ID);
Hope this Helps!!
Upvotes: 1