Udostępnij za pośrednictwem


Hitting the Enter Key to submit a form in ASP.Net

So in my latest adventures I was tasked with creating a form that had 1 text box and a button that made a query once entered.  Straight forward enough right?  No problem  in no time the form was created and the page submitted the query and returned the results.  I submitted my code to the team for testing and one piece of feedback they pointed out was the fact that they wanted to hit the "Enter" key whenever they were done typing and have the page submit.  This is nothing new and in fact not an uncommon request. In the past I would have whipped out some javascript to make it happen, which I didn't feel like doing this time given the page I was creating was to be run in SharePoint and introducing JavaScript to a SharePoint page is not one of the most desireable things when it comes to development. Given this is not an uncommon request I began to think,  there has to be a better "ASP.Net" way to do this.  An sure nuff after a little digging I was introduced to the "defaultButton" property.  This can be applied to a asp:Form or asp:panel and will allow to to determine which button event should be triggered when the user hits the enter key.  This really works well if your form has 1 textbox like mine did.  So I went ahead and added a panel to my form (as the form object it self was not available to be inside of a content page)  then added the "defaultButton" property and specified which button should trigger when the user hit "Enter".  If you are not using master pages then the "form" object might be useful for you as well.

<asp:panel defaultbutton="button2" runat="server">
        <asp:textbox id="textbox3" runat="server"/>
        <asp:button id="button2" runat="server"/>
    </asp:panel>

For more one this property check out: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx or https://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx

Happy coding!

Comments

  • Anonymous
    April 26, 2013
    This solved my issue :)

  • Anonymous
    June 11, 2013
    thanks it works

  • Anonymous
    July 08, 2014
    Excellent Easy Fix with minimal coding.  Thanks