Code: Setting the DefaultButton property for a PasswordRecovery control in ASP.Net
-
Getting ASP.Net to handle Enter keypresses on a page that has more than one logical “form” has a generally easy solution in .Net 2.0+: just wrap each group of controls in an ASP Panel, set its DefaultButton property to the ID of the proper submit button.
PasswordRecovery contains the button we want to use (called SubmitButton, SubmitImageButton, or SubmitLinkButton, depending on the SubmitButtonType property), so let’s specify it.
1 2 3
<asp:panel id="prPanel" runat="server" defaultbutton="SubmitImageButton"> <asp:passwordrecovery id="pr1" cssclass="prStyle" runat="server" submitbuttontype="Image" submitbuttonimageurl="/images/submit.gif"></asp:passwordrecovery> </asp:panel>
But the PR’s button isn’t within the scope of our Panel, so we get an error: The DefaultButton of ‘prPanel’ must be the ID of a control of type IButtonControl.
We need to give the Panel the complete path to the button. Matthew’s post uses the code-behind to set the DefaultButton property to the button’s UniqueID, which has the full “path.” However, that yielded the same error for me.
The solution is to set DefaultButton to the nested button’s UniqueID, but to remove any nodes that are above your Panel’s scope (in the case above, “ctl00$contentArea$”):
1 2 3
<asp:panel id="prPanel" runat="server" defaultbutton="pr1$UserNameContainerID$SubmitButton"> <asp:passwordrecovery id="pr1" cssclass="prStyle" submitbuttontype="Image" submitbuttonimageurl="/images/submit.gif" runat="server"></asp:passwordrecovery> </asp:panel>
Now you don’t have to do something clumsy like convert your PasswordRecovery control to a template and nest your Panel in there (which swaps out 3 lines for 30).
Things to keep in mind:
- UserNameContainerID is the constant name of a container control within PasswordRecovery; it’s not a control that I named.
- Remember to change the last part of your ID to SubmitImageButton or SubmitLinkButton if you’re using type=Image or type=Link, respectively.
This has broader applications beyond just PasswordRecovery, so you can use it anytime you need a scoped ID for any control that’s nested within other controls.





October 16, 2008 at 4:35 am
does this work?
October 17, 2008 at 4:53 pm
It worked for me, amazingly enough.
April 14, 2009 at 6:30 am
It worked for me as well - many thanks!
June 1, 2009 at 2:00 pm
Give this man a gold star! I have been fishing for a fix to this problem for 2 days! This isn’t easy to figure out or find the answer, but it worked…
just an FYI, can you change your background color? hard to read :P
July 6, 2009 at 6:05 pm
Thanks for sharing this, Jeremy. This issue had me stumped until I found your post here.