Thoughts, Tips and Tricks on what I'm currently do for a living. Currently most of my spare time is spent on contributing to Akka.NET.

Thursday, February 8, 2007

Don't access the property ClientId to early

The ClientId property on a Control is correct only after the control has been added to a Parent, i.e. added to a Controls collection. The parent must also be connected to a parent, and it's parent, and so on up al the way to the Page control. If you try to get ClientId to early, not only will you get something unusable, it will be cached so all subsequent calls will get the same. It will also prevent postback events from working. Big No-no:
public class MyControl : CompositeControl
{
 protected override void CreateChildControls()
 {
  Button myButton = new Button();
  myButton.Text = "Unclicked";
  myButton.Click += new EventHandler(myButton_Click);
  Controls.Add(myButton);
  
  //MyControl has no parent yet. The following code will prevent
  //the myButton_Click from beeing called when the button is clicked.
  //Remove the line and it will be called.
  string id = myButton.ClientID; 
 }
 
 void myButton_Click(object sender, EventArgs e)
 {
  Button button = (Button)sender;
  button.Text = "clicked";
 }
}
Another example: http://aspadvice.com/blogs/joteke/archive/2007/01/28/Accessing-ClientID-or-UniqueID-too-early-can-cause-issues.aspx

No comments:

Post a Comment