Wednesday, December 5, 2007

DefaultButton, DefaultFocus and UniqueID vs ClientID

Wow, now I just stumbled upon something rather confusing.  I discovered one of my screens was deleting records by default (confirmation prompt of course) when users pressed ENTER so I went to set the DefaultButton to something more appropriate.  While I was at it, why not set the DefaultFocus too?  So I added the following code:

 

Page.Form.DefaultButton = btnComponentSearch.UniqueID

Page.Form.DefaultFocus = txtComponentName.UniqueID

 

That fixed the button, but the focus wasn’t working so I changed focus to

 

Page.Form.DefaultFocus = txtComponentName.ClientID

 

To my surprise it worked!  Then I thought…what happens if I change the DefaultButton:

 

Page.Form.DefaultButton = btnComponentSearch.ClientID

 

That resulted in the following error:

The DefaultButton of 'form1' must be the ID of a control of type IButtonControl.

 

So it could no longer find the control, how confusing…until I read this article about Naming:

 

Rendered name attributes correspond to UniqueID property and id attribute to ClientID property.

 

So gist is: VB.Net understands UniqueID, but for Javascript-ish stuff, you’ll need ClientID (except for the DefaultButton – which uses both J ).  Pretty crazy!

1 comment:

Anonymous said...

Glad I found this post. A number of sources were telling me to use the UniqueId for DefaultFocus, but it just wasn't working.

I would never have thought to use ClientId.