ASP.Net - Button Default

ASP.Net 1.0

For ASP.Net you can do something like this. But for ASP.Net 2.0 there are simplier ways to accomplish the same activity.

When someone presses enter on a certain button - do you want it to do a certain thing?

Here’s what to do…

Put this into your page design.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script language="javascript">
function KeyDownHandler(btn)
{
// process only the Enter key
if (event.keyCode == 13)
{
// cancel the default submit
event.returnValue=false;
event.cancel = true;
// submit the form by programmatically clicking the specified button
btn.click();
}
}
</script>

Add a button to your form, and hook up the logic that should be executed when someone presses the enter button. (In my example I created a button named btnQuickFind )

Add a onKeyDown element to the controls you want to add the behavior. For example

1
2
3
<asp:textbox id="txtFinder" runat="server" AutoPostBack="True" 
Width="72px" onKeyDown="KeyDownHandler(btnQuickFind)">
</asp:textbox>

Now… if the person presses the enter box while focus is in that control - a simulated btnQuickFind keyclick will be activated.

To Turn off the Enter button you can do the following

1
2
3
4
5
6
7
8
9
10
11
12
13
<head>
<script type="text/jscript" language="jscript">
function ourClick()
{ if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
}
</script>
</head>
<body onkeydown="ourClick()">
:

ASP.Net 2.0

ASP.NET 2.0 introduced a concept of a “default button”. The defaultbutton attribute can be used with

or asp:panel control. What button will be “clicked” depends of where actually cursor is and what button is chosen as a default button for form or a panel.

Here is sample HTML code that contains one form and one panel control:

1
2
3
4
5
6
7
8
9
10
11
12
  <form defaultbutton="button1" runat="server">
inside form
<asp:textbox id="textbox1" runat="server"/>
<asp:textbox id="textbox2" runat="server"/>
<asp:button id="button1" text="Button 1" runat="server"/>

<asp:panel defaultbutton="button2" runat="server">
inside panel
<asp:textbox id="textbox3" runat="server"/>
<asp:button id="button2" text="Button 2" runat="server"/>
</asp:panel>
</form>

On any field in the form, if you press Enter, it would do the same thing as pressing the ‘Button 1’ button. The exception is the controls inside the Panel. If you press the Enter button on textbox3, then it would have the same effect as executing the function associated with ‘Button 2’.