My blog has moved!

Visit http://blog.adamroderick.com/ and update your bookmarks.

Tuesday, January 27, 2009

Setting the Page's Default Button from a User Control

ASP.NET 2.0 has a feature that allows you to set a default button for a form or a panel. I ran into a requirement to set the default button for the page's form from within a user control. I found that using the button's UniqueID property instead of ID or ClientID did the trick.


// the user control's Page_Load event handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// works
Page.Form.DefaultButton = Button1.UniqueID

// does not work
// Page.Form.DefaultButton = Button1.ID

// does not work
// Page.Form.DefaultButton = Button1.ClientID
}
}


Using ID or ClientID resulted in the exception "The DefaultButton of ‘form1′ must be the ID of a control of type IButtonControl." This just means the page couldn't find a button control using the ID you gave it. It needs the UniqueID to find the control.

The reason that UniqueID must be used is because UserControl inherits from TemplateControl, which implements the INamingContainer interface. This causes any control within a user control to be renamed to ensure uniqueness of names across all of a page's user controls (or any other naming container).

Labels: