Validator nightmare on dynamic control C#

One Monkey picture One Monkey · May 14, 2009 · Viewed 8.5k times · Source

I have a requirement to add a RequiredFieldValidator and RegularExpressionValidator to a dynamically created textbox in a dynamically generated tablecell, inside a Web User Control in the Content Area of a Page created from a Master.

The problem, as you can probably guess, is trying to dynamically set the ControlToValidate property to look at my dynamically created text box.

After some research the code now:

  • Creates a Panel (As I have heard the ControlToValidate and Validator must be within the same container). This was originally a placeholder but was trying a suggestion listed below.
  • Creates the Textbox and sets its ID.
  • Adds the Textbox to the Panel.
  • Creates the RequiredFieldValidator.
  • Sets the id of the ControlToValidate. Values I have attempted to use:

    • The ID of the control
    • the ClientID of the control
    • the ID of the control prefixed by the added text the server appends to child controls of the Web User Control
    • the Client ID modified the same way
    • the name of the control (on the off chance)
    • the name of the control prefixed by the text the server adds to the names of controls
    • using a bespoke Recursive FindControl Method in an attempt to cast a new Control object to Textbox and then using its ID and ClientID
    • the UniqueID of the control
    • the same modified with the prefix as detailed above
  • Add the validator to the panel.
  • Add the panel to the tablecell.

Needless to say I am still unable to convince the Validator to "see" the control it is supposed to validate and I am completely out of new ways to approach the problem.

EDIT: Further detective work has lead me to the point that the page doesn't have a problem until the page_load event has finished. The server seems to have a problem after the code for building the page has finished executing. I'm starting to wonder if I'm actually adding the controls into naming containers much too late instead of too early.

Any suggestions?

Answer

pgb picture pgb · May 14, 2009

What about creating a user control that contains the textbox and the two validators? Then you can set the ControlToValidate via Visual Studio, as usual, and then dynamically add this new control to your tablecell dynamically.