Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

Default Focus When Using Master Pages

ASP.NET 2.0 introduced two very important features which are DefaultFocus and DefaultButton. In this post I will talk about DefaultFocus. The DefaultFocus allows you to focus on the element. This is primarily useful when you want the page to load and focus on the TextBox.

If you are using pages without master pages all you need to do is to add defaultFocus attribute in the form tag.

<form id="form1" defaultfocus="txtUserName" runat="server">

However, this approach will not work when you are using the pages which inherit from the master page. The reason is not that the content pages does not have a form tag but the reason is that the ID is different when the content pages are rendered.

Let's say that in your content page you have a textbox named txtUserName. Now, you want that when the page is loaded the focus will be on the txtUserName textbox. For this you add the defaultFocus attribute in the master pages form tag like this:

<form id="form1" runat="server" defaultfocus="txtUserName">

Now, you run your content page but the focus is not set. Right click on the page and view source. You will notice that the ID is not txtUserName but it is something like id="ctl00_ContentPlaceHolder1_txtUserName" (Offcourse it depends on what you name your content place holder).

So, you can fix it by using the full name in the defaultFocus attribute like this:

<form id="form1" runat="server" defaultfocus="ctl00_ContentPlaceHolder1_txtUserName">

Now, if you run the page the textbox wil be focus correctly. Although the solution works but I would suggest a different approach. You can use [ControlID].Focus() to focus on the control that you want. This way the WebForm_AutoFocus('txtUserName'); function which is automatically generated when Focus is called will not be fired with all the content pages.

 

Published Tuesday, January 09, 2007 11:27 PM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Default Focus When Using Master Pages @ Thursday, January 11, 2007 5:52 PM

could you not use defaultfocus="<%= txtUserName.ClientId %>"?

Betty

# re: Default Focus When Using Master Pages @ Thursday, January 11, 2007 6:15 PM

Hi Betty,

The expression will not evaluated when the page loads and hence it will not insert the WebForm_AutoFocus function. Hence, the textbox will not be focused.

Thanks,

Azam

azamsharp

# re: Default Focus When Using Master Pages @ Friday, January 12, 2007 9:40 AM

I believe it is possible to set that property from the code behind as long as it is done early enough though. Brendan

Brendan

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below