6

i am programatically adding Webcontrols in to a User Control i am also adding a javascript event passing the controlID as a parameter but the clientID is the one i assigned a it does not contain the one that asp.net generates

   var txt = new TextBox();
   txt.ID = "MyID"+Number;

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");

i can workAround this by adding the parent control ID

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" + this.ClientID+"_"+txt.ClientID + "');");

On which Page life cycle are the Client IDs generated?

1
  • Client Ids are by far one of the most obnoxious things to deal with in webforms, if I had to make solely 1 argument of why the MVC framework is substantially better than webforms it would be this argument that you dictate the ids not depend on ASP.net to assign whatever it feels like. Nov 18, 2008 at 22:38

2 Answers 2

8

You need to add the control to the control hierarchy before you add the attribute.

   var txt = new TextBox();
   txt.ID = "MyID"+Number;
   Controls.Add ( txt );
   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");

ControlCollection is no ordinary collection; it notifies the owner control when controls are added, and the control can take appropriate actions.

0
2

You should be able to add the attribute during OnPreRender(). INamingContainer is so painful sometimes...

1
  • this solution works for me since i was having <% %> code blocks and does not allow me to add the created control to this.Controls Thanks Nov 18, 2008 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.