ASP.Net defaultfocus and defaultbutton in Master Pages

By | 2008-03-03

One of the big problems I faced in .Net 1.1 web applications was capturing the enter key so that the correct asp:button would be “clicked.”

To solve this problem, ASP.Net 2.0 lets you specify this on the html form element with the defaultfocus and defaultbutton attributes. This is really slick and works like a charm.

But what if you want to user a master page and specify the default focus or button from your content page?

In your code behind you can simply put:

    Page.Form.DefaultFocus = txtFirstName.ClientID;
Page.Form.DefaultButton = btnSave.UniqueID;

The catch here is to remember that when the page is rendered, your controls’ ids will be prefixed because they’re in a naming container. So make sure you use the ID fields that will be correct at that time (ClientID and UniqueID).

Leave a Reply

Your email address will not be published. Required fields are marked *