add

Friday, March 13, 2009

How to change default button of ASP.NET Page

ASP.Net 2.0 has a new feature of setting default button of a asp.net page.
Now you can set initial focus on your form and also set a default button (for when pressing enter) by setting 2 attributes on your form tag:

defaultbutton="Button1" defaultfocus="TextBox1"

This will add JavaScript to set focus on TextBox1 and set the Button1 as the default button for when a user presses enter on the web form.

This is very neat, but when using master pages you don't have access to the form tag. As of any property, you can also set it at the code behind, but you need a little trick. Since ASP.NET uses javascript to set the focus and the default button, you have to specify the client id of the controls, rather than the server ids:

Page.Form.DefaultButton = Button1.UniqueID;
Page.Form.DefaultFocus = TextBox1.ClientID;


Happy Programming!!

No comments: