Default Focus, Buttons and Validation Errors with ASP.NET 2.0
One of the common requests with ASP.NET 1.1 today is to have better control over what happens when a user in a browser hits the enter key without having a button or post-back control selected.
ASP.NET 2.0 makes this easier by supporting the concept of a "default button" that can be indicated on either a <form> or <asp:panel> container control. If no button is selected at the time the enter key is selected, the defaultbutton property will drive the appropriate post-back to the server and route the message to the control you want.
<html>
<body>
<form defaultfocus=“textbox2” defaultbutton=“button1” runat=“server”>
<asp:textbox id=“textbox1” runat=“server”/>
<asp:textbox id=“textbox2” runat=“server”/>
<asp:button id=“button1” text=“Same Page” runat=“server”/>
<asp:panel defaultbutton=“button2” runat=“server”>
<asp:textbox id=“foo” runat=“server”/>
<asp:button id=“button2” runat=“server”/>
</asp:panel>
</form>
</body>
</html>
· Here if the enter key is selected the first time the page is loaded, "button1" will be the button that receives the post-back event.
· If the enter key is hit while the user has their cursor focus within the "foo" textbox (contained wtihin the <asp:panel>), then "button2" will be the button that receives the post-back event.
There is a catch in this feature, when the page is using Master Page. In this case, below would be required to handle the situation.
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.DefaultButton = Button2.UniqueID;
}
protected void Page_PreRender(object sender, EventArgs e)
{
Page.SetFocus(TextBox2);
}
Thanks & Regards,
Arun Manglick || Tech Lead
I agree. "DefaultButton" is a kool feature especially since we can use it for individual panels.
ReplyDeleteHowever, this can create issues sometimes, if used with multiline textboxes on your page..
There is again a catch to the above mentioned approach.
ReplyDeleteCatch -
Let say you have two buttons viz. Save & Cancel (Default Button).
Now, bring the focus on page or on some other control on the page, except these two buttons.Now press 'Enter'. This will fire the 'Cancel' button - The Correct behavior.
Now, bring the focus on 'Save' button using tabs. Now press 'Enter'. This will again fire the 'Cancel' button and not the 'Save' button - The InCorrect behavior.
To overcome this best is to use below in the Page_Load.
Page.RegisterHiddenField("__EVENTTARGET", "MyDefaultButton");
Hope this helps.
Arun (Blog Author)