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"/>


In your .aspx.cs add the following:

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


Stefan said...

thanks, that was very helpful. i was trying to assign a skinid to the createuserbutton and your code helped me do it.

Golden State Girl said...

AWESOME! This has been a problem for me for months. I finally got enough complaints from users that I decided I had to fix it. I was prepared to waste a lot more time figuring out how to do it. This code was all I needed.


Katerina said...

Thank you so VERY MUCH!!! Clicking the CreateUser Button was raising the NextButtonClick event, although there was no NextButton! Now everything works just fine! Fingers crossed... :)

Chris Lo said...


I wonder if someone could please give me the VB version of this? I can't seem to get it.

Many thanks,

Sreedhar said...

Saved my day