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.
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