Sunday, 3 December 2006

In custom control the ID property of child controls must be unique

When we create a composite web custom control, often we create child controls in the override CreateChildControls() method. At this time we assign a text value to ID property of each child control. There is a little bit tricky of this ID property. The ID value should be unique across the whole page, not only in the control itself. Say if we have a TextBox with ID "txtValue", when we put two controls in a page and call FindControl("txtValue"), the runtime throws an exception says there are multiple controls have the same txtValue ID value. This is because asp.net assign the same txtValue to two text box in a same page.

To solve this problem, we alway prefix the control's client id with the child id to ensure uniqueness. For example, we can set this.ClientID + "txtValue" to the TextBox ID property. Because the ClientID of a custom control is unique, the ID of each child control is always unique too.

No comments: