Tuesday, 3 July 2007

Default Button in ASP.NET

Many times we require setting a default button for a web form. Such as for search forms or login page where users enter a value into the textbox, then press the enter button. If you are developing in ASP.NET 1.x, the page will refresh, but nothing will happen. The buttons click event wont fire UNLESS; you explicitly enable a default button.

In ASP.NET 1.x:

You can set a default button by simply adding the following line to your page's Load event, replacing "btnSearch" with the name of your button. It uses a hidden Page method called RegisterHiddenField and works splendidly:
Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")

In ASP.NET 2.0:

You can do this very easily, unfortunately its not that widely used, much less known. The HtmlForm object has a property DefaultButton. This property gets or sets the control that that causes the post back when the ENTER key is pressed.

Example:
<body>
<form id="form1" runat="server" Defaultbutton="processRequestButton">
<div>
<asp:TextBox AccessKey="c" runat="server" ID="somevalueTextbox">
</asp:TextBox>
<asp:Button runat="server" ID="processRequestButton" Text="Process" OnClick="processRequestButton_Click" />
</div>
</form>
</body>


kick it on DotNetKicks.com

No comments:

Post a Comment