ASP.NET dynamic controls and validators – Unable to find control id ‘…’ referenced by the ‘ControlToValidate’ property of ‘…’

asp.netupdatepanelvalidation

I have seem many forum posts / responses on this subject but I am no closer to a solution.

I am loading a repeating data structure from the DB into UpdatePanel controls in an event handler. The number of repeats varies so controls are all created and added to a container panel dynamically. The user has the ability to edit the data so I am also dynamically creating validator controls (RegularExpressionValidators)

The problem is in setting the ControlToValidate property of the validator. No matter how I set this I get the Unable to find control id '...' referenced by the 'ControlToValidate' property of '...' error response from the server which is then raised by ASP.NET AJAX JS.

The short version of the control adding code looks like this:

TextBox licenseCode = new TextBox();
licenseCode.ID = this.getNextId();  // generated ID contains only [A-Za-Z], [0-9], :, -, .
licenseCode.MaxLength = 50;
this.purchaseEdit.Controls.Add(licenseCode);  // this.purchaseEdit is an asp:Panel

RegularExpressionValidator licenseCodeVal = new RegularExpressionValidator();
licenseCodeVal.ControlToValidate = licenseCode.ClientID;
licenseCodeVal.ID = this.getNextId();
licenseCodeVal.ValidationGroup = this.purchaseEditSave.ValidationGroup;  // save button within the panel
licenseCodeVal.ValidationExpression = @"^.{1," + licenseCode.MaxLength.ToString() + "}$";
licenseCodeVal.ErrorMessage = "Between 1 and " + licenseCode.MaxLength.ToString() + " chars.";
this.purchaseEdit.Controls.Add(licenseCodeVal);

As you can see both controls are added to the same container, the validator is added after the TextBox, and the ControlToValidate property is currently set to the ClientID of the TextBox. I have tried the ID value too but no joy.

The really irritating thing is that if I don't add the validator, and using a breakpoint inspect the ClientID of the TextBox, I can inspect the DOM of the updated page and find the ID attribute of the TextBox:

<input type="text" id="ctl00_ContentBody_PCTL::4890cc3a-8d07-4dee-aa9f-bdd8735fcaf8::licCode"... />

As far as I can tell I'm not doing anything wrong, so why am I getting this error??

Any suggestions much appreciated.

Best Answer

You should not use the ClientID but the ID of the TextBox.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx

"I have tried the ID value too but no joy."

But you didn't get an exception and only the validation didn't work?!

My suggestion is to wrap the control and the validator in an UserControl and add this dynamically to your container-control. On this way you can use fix ID's because they all have distinct NamingContainers.

The code will be cleaner. Encapsulation also increases reusability.