Programmatically Submit Form on Enter Key in C#

By default, a majority of the pages and all the functions on a C# Web Application page are all contained within a single form element. Therefore, there may be multiple buttons or other postback controls within a single form. And this may be the reason why there isn’t by default a control which is automatically called when the web users hits the ENTER button.

To Assign a Default On a Standard C# Webpage

This is the default way and involves the name of the control. If you have a ASP Button called btnSearch, the code you would include in the Page_Load function.

this.Form.DefaultButton = “btnSearch”;

To Assign a Default On a Content Page (from a MasterPage) C# Webpage

If your Web application uses MasterPages and you want to assign a control to submit the form on the Enter key, you concept is the same as above, but you’ll need to pass the UniqueId of the control. Assume a control called btnSearch on a ContentPage, add the following to the Page_Load function.

this.Form.DefaultButton = btnSearch.UniqueId;

Some benefits to programmatically assigning the Enter key is your ability to change which Postback function to assign based on how the web user enters the page. Other than that, assigning the default submit control is a major convenience factor for web users.

References:
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

One Response to “Programmatically Submit Form on Enter Key in C#”

  1. Mario says:

    This doesn’t seem to work. I am using studio 08 and VB, but I would expect the concept to be the same.

    btnLogin.UniqueID = ctl00$ContentPlaceHolder1$btnLogin
    btnLogin.ID = “btnLogin”

    When either of these are used, the button click does not fire.

    I tried ClientID which gives “ctl00_ContentPlaceHolder1_btnLogin”

    This looked more logical to me, but it gives an error
    “The DefaultButton of ‘form1′ must be the ID of a control of type IButtonControl.”

    I have searched for this error and i come up with a lot of extra logic that seems too much. There must be an easier way.

    Any ideas?

Leave a Reply