Set DefaultButton for Enter KeyPress in ASP.NET

Have you ever tried to set the default focus and default submit button on an ASP.NET 2.0 Password Recovery Control? It takes some work, yet I was able to put this example together thanks to Spannjaars.com, Ellipse in the asp.net forums, and Google.

Aspx page

<asp:PasswordRecovery ID="PasswordRecovery1" runat="server"OnVerifyingUser="PasswordRecovery1_VerifyingUser" />

Code behind (.cs)

protected void Page_Load(object sender, EventArgs e)
{
   // The first time our page loads we place the cursor in the
   // User Name textbox and make the Submit button the default button 
   if (!IsPostBack)
   {
      Page.Form.DefaultButton = PasswordRecovery1
         .FindControl("UserNameContainerID$SubmitButton").UniqueID;
      Page.Form.DefaultFocus = PasswordRecovery1
         .FindControl("UserNameContainerID$UserName").ClientID;
   }
}

protected void PasswordRecovery1_VerifyingUser
                  (object sender, LoginCancelEventArgs e)
{
   // This event fires after the User Name is entered; Place the cursor 
   // in the answer textbox and make the Submit button the default button 
   Page.Form.DefaultButton = PasswordRecovery1
      .FindControl("QuestionContainerID$SubmitButton").UniqueID;
   Page.Form.DefaultFocus = PasswordRecovery1
      .FindControl("QuestionContainerID$Answer").ClientID;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s