Friday, December 28, 2007

"Fixing" the Enter Key in CreateUserWizard

Problem: You find that when you press the "Enter" or "Return" key on a page that contains the CreateUserStep of your CreateUserWizard (or any other step of any other wizard), your form does not get submitted.  Put another way, something else on the page gets triggered instead of your Create User button.

Solution: In ASP.NET 2.0 the Page.Form has a new property: DefaultButton.  This effectively traps the Enter key and causes the specified button to execute its onclick event handler.  We would like to set this Page.Form.DefaultButton property to the UniqueID property of the CreateUserStep's Create User button.  Unfortunately, we do not have a reliable way of accessing this button in our code-behind.  The solution is to replace it with our own button and wire up the DefaultButton property in the button's pre-render event handler, since it is in a template and we cannot access it directly.

In your .aspx add the following CustomNavigationTemplate to your CreateUserStep:

<CustomNavigationTemplate >
     <asp:Button ID="CreateUserButton" OnPreRender="CreateUserButtonRender" runat="server" Text="Register User" CommandName="MoveNext" ValidationGroup="CreateUserWizard"/>
     </CustomNavigationTemplate>

 

In your .aspx.cs add the following:

protected void CreateUserButtonRender(object sender, EventArgs e)
{
  this.Page.Form.DefaultButton = (sender as Button).UniqueID;
}