Jonas Stawski

Everything .NET and More

Set Focus on a TextBox and Set a Default Button

ASP.Net 2.0 has a new feature (I learned about it today) and I must say it’s a pretty cool feature one that every web developer had to deal with since the very beginning. 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!!

Comments (16) -

very good

Reply

Very helpful. Thank you

Reply

thanks.It was of great help

Reply

Simple thing, but of gr8 importance.Thanq....

Reply

Nice finding bro........

Reply

Nice sir,, It'sVery useful..........

Reply

How about if it is a dynamic added control ?

Reply

Vi,
    You would do the same thing. In the code behind you would do
Page.Form.DefaultButton = DynamicAddedButton.UniqueID;
Page.Form.DefaultFocus = DynamicAddedTextBox.ClientID;

Reply

Hi,

How can set those property through javascript? Since I need to set defaultbutton property on some condition based.

Thanks

Reply

What ASP.NET does is create the javascript that will set focus on those controls. If you need to set focus on a control all you have to do is call
var obj = document.getElementById("Textbox1");
if (obj)
   obj.focus()

Reply

That was inspiring,

A very interesting and helpful article to set focus on a textbox,

Keep up the good work,

Thanks for writing, most people don't bother.

Reply

Thanks mate nice work !

Reply

I write this code on page load event...
Page.Form.DefaultFocus=txtUserName.ClientID;

Page.Form.DefaultButton=btnLogin.UniqueID;
Its working fine in Google Chrome, But in IE and Firefox, entire page is getting scroll up...Page is visible from the control on which the focus is set...website header is getting hide

Reply

Trying out right now...will be happy if it works...thanks again..

Reply

Add comment

biuquote
Loading