You might have noticed that when you press enter to submit a form in your asp.net page it just refreshes the page instead of submitting as you would expect.
The reason behind this is that asp.net web forms uses the <form> html tag to power the whole postback mechanism. This means that the default behaviour of submitting the form is still occurring but as far as asp.net is concerned you have just submitted its postback form with no commands so it just refreshes.
Anyway enough of the back story. The way around this is to set the DefaultButton property. The DefaultButton property was added to the HtmlForm and Panel classes in asp.net 2.0.
You can set this programmatically:
Panel1.DefaultButton = Button1.UniqueID;
or via the code markup:
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1"> </asp:Panel>
The best use of the DefaultButton property is at the Panel level. The asp.net webforms postback model defines a single html form that all elements of the page are contained in.
If you have for example a login button and a search box in your masterpage, a feedback form in the content area then you have several logical forms contained behind the scenes in a single html form tag. Your users will expect to press enter in the search box and trigger a search. They dont want to see your feedback form validators kicking up a fuss.
By putting each logical form inside an
At the form level
As I have already hinted you can also do this at the page level by setting the DefaultButton on the behind-the-scenes page level form tag. As you will already see this is not a good idea for serious projects but you may want to set it in certain circumstances.
If you are in a content page of a masterpage then you will need to do it in the code behind:
this.Form.DefaultButton = this.Button1.UniqueID;
As an added bonus you are also improving the experience of visually impaired or otherwise disabled visitors. By defining the default button you are helping the screen reader software to have a fighting chance at understanding your asp.net page.
Gotcha - Buttons and ImageButtons only (not LinkButtons)