Default Button - Click Enter Key to Activate

« View all ASP.net articles

February 06, 2007

Related Content
• Set Focus using Access Keys ( like ALT+A)
• Set Focus to a TextBox Control

You can easily designate a default button on a page so when a user presses the Enter button it will activate. If you do not designate a default button, when the Enter button is clicked the button's click event will not be fired off.

To do this, you simply set the defaultbutton property of the form.

In this example, when the btnDefault button is clicked the lblHere label becomes visible. If you do not set the defaultbutton property of the form, the button click event would not be activated and basically nothing would happen.

Form
<form id="frmDefaultButton" defaultbutton="btnDefault" runat="server">
   <asp:Button ID="btnDefault" runat="server" Text="myButton" />
   <br /><br />
   <asp:Label ID="lblHere" runat="server" Text="Here I am"></asp:Label>
</form>
Code-behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   lblHere.Visible = False
End

Sub Protected Sub btnDefault_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDefault.Click
   lblHere.Visible = True
End Sub