[ASP.NET] Setting the DefaultButton for a Login control
Background
One underused feature in ASP.NET 2.0 is the ability to set a default button for a form. In the past, this often required some extra JavaScript, and was just enough of a pain that it didn't get done until someone asked for it. The ASP.NET form element has DefaultButton and DefaultFocus properties which do exactly what you'd think. For instance, a site I'm working on has a search bar in the header, so I added the following to the form control. Default focus goes to the search textbox, and pressing the enter key submits the form.
<form id="MainForm" runat="server" DefaultButton="Search" DefaultFocus="SearchText">
In my case, the form is declared in my site's MasterPage, You might not want to do that depending on how many forms are in your site; this site's got very few, so it's simpler to set it globally and handle the exceptions. Unless I say different, every page will focus the search textbox and the search button will handle the enter keypress.
Overriding DefaultButton in Page
There are two few ways to override DefaultButton and DefaultFocus. You can override in your codebehind:
this.Form.DefaultButton = MyButton.UniqueID;
In addition to the Form, you can also set the DefaultButton in an <asp:Panel>. That's handy because you can nest Panels, and Panel with the current focus gets to set the Default button, bubbling up until you get to the form.
Gotcha! Containers mangle control ID's, but that's what DefaultButton requires
I ran into this on a simple login form. When the user's logging in, we want to make sure the default button is set to submit the login form, but since the login button is generated by a template, we don't have an ID to work with. The solution is to reference the parent control's id (the <asp:Login> control), then add the $, then add the ID of the actual control. You can find the ID of the control by viewing source if you're not sure.
<asp:LoginView ID="LoginView" runat="server"> <LoggedInTemplate> <div> You are logged in as <asp:LoginName ID="LoginName" runat="server" /> </div> <div> <asp:LoginStatus ID="LoginStatus" runat="server" /> </div> </LoggedInTemplate> <AnonymousTemplate> <asp:Panel ID="panelLogin" runat="server" DefaultButton="Login$LoginButton"> <asp:Login ID="Login" runat="server" /> </asp:Panel> </AnonymousTemplate> </asp:LoginView>