Default Control Focus with ASP.NET Master Pages and LINQ

Posted by: Malcolm Sheridan , on 2/20/2009, in Category ASP.NET
Views: 35822
Abstract: The following article demonstrates how to use Master Pages and LINQ to automatically set the control that receives focus when a page loads.
Default Control Focus with ASP.NET Master Pages and LINQ
 
One handy tip to remember when developing an ASP.NET website is to set a control to receive focus automatically when the page loads. This makes it more convenient for the end user as they don’t have to manually move the mouse and click the first control. 
Instead of using JavaScript to set this for every page, this article will demonstrate how to do this by using Master Pages and LINQ.
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
Add a Master Page to the project. Once that is completed, add a Web Content Page and select the newly created Master Page as the Master Page.
Open the HTML mark-up in the new page and create a simple HTML table, drag and drop two text boxes and a button on the page to create a simple form. The following code is an example of this simple form:
<table style="width: 400px;">
        <tr>
            <td>Given Name</td>
            <td><asp:TextBox ID="txtGivenName" runat="server" /></td>       
        </tr>
        <tr>
            <td>Surname</td>
            <td><asp:TextBox ID="txtSurname" runat="server" /></td>
        </tr>
        <tr>       
            <td>&nbsp;</td>
            <td><asp:Button ID="btnSave" runat="server" Text="Save Data" /></td>
        </tr>
    </table>
Note: For doing layouts, use <div>’s over tables.
When the page loads, instead of the user manually moving the mouse and placing the cursor in the Given Name textbox, we’ll write this code in the Page Load event in the Master Page. This ensures that we will only have to write this code once and any page that is a child of the Master Page will automatically inherit this functionality. This example utilizes LINQ to query the ContentPlaceHolder in the webpage and find the first TextBox control. The following code will be executed in the Page Load event:
C#
protected void Page_Load(object sender, EventArgs e)
        {
            var control = ContentPlaceHolder1.Controls.Cast<Control>()
                          .Where(o => o is TextBox)
                          .FirstOrDefault();
 
            if (control != null)
            {
                control.Focus();
            }
        }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
                  Dim control = ContentPlaceHolder1.Controls.Cast(Of Control)().Where(Function(TypeOf o) o Is TextBox).FirstOrDefault()
 
                  If control IsNot Nothing Then
                        control.Focus()
                  End If
End Sub
The FirstOrDefault method is used because there might be pages that do not contain a TextBox control. When none is found, null is returned. To see how this code is sent to the client, run the website and view the HTML source. Scroll to the bottom of the code and you’ll find the following JavaScript:
 <script type="text/javascript">
 //<![CDATA[
 WebForm_AutoFocus('ctl00_ContentPlaceHolder1_txtGivenName');//]]>
 </script>
 
The WebForm_AutoFocus method is part of the WebReference.axd file. This file is referenced via the script tag at the beginning of the HTML. The following is an example of the script path:
<script src="/WebResource.axd?d=aJEJQD1ZsUmPBPzsaC59Dw2&amp;t=633628781190633238" 
type="text/javascript"></script>
 
The reference enables the page to call the WebForm_AutoFocus method. If you browse to the axd file, you’ll find the WebForm_AutoFocus method:
function WebForm_AutoFocus(focusId) {
    var targetControl;
    if (__nonMSDOMBrowser) {
        targetControl = document.getElementById(focusId);
    }
    else {
        targetControl = document.all[focusId];
    }
    var focused = targetControl;
    if (targetControl && (!WebForm_CanFocus(targetControl)) ) {
        focused = WebForm_FindFirstFocusableChild(targetControl);
    }
    if (focused) {
        try {
            focused.focus();
            if (__nonMSDOMBrowser) {
                focused.scrollIntoView(false);
            }
            if (window.__smartNav) {
                window.__smartNav.ae = focused.id;
            }
        }
        catch (e) {
        }
    }
}
It’s always a good idea to look at the HTML that is being sent to the end user. Remember, less code is far often better. Separate JavaScript was not created to do achieve this, we simply wrote some LINQ code on the server and utilized the power of ASP.NET, and that’s pretty cool if you ask me!
 
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email 

Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET.  

 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Natalie on Saturday, February 21, 2009 8:31 AM
Way coool!
Comment posted by Iain Waddell on Thursday, October 8, 2009 10:43 AM
Excellent article but the VB.NET code has a typo. Eventually translated the C# code to give:

Dim control = ContentPlaceHolder1.Controls.Cast(Of Control)().Where(Function(o) TypeOf o Is TextBox).FirstOrDefault()
Comment posted by Suprotim Agarwal on Wednesday, October 28, 2009 10:00 AM
Iain: Thanks. I use a code convertor and that must have goofed up the vb.net code
Comment posted by Peterson on Sunday, February 20, 2011 8:25 AM
Thanks for your article. But I have a question. If I need to put the focus in a textbox disabled=true only? Because in my form, I have 2 textbox, the first is disabled and the second is enabled.
Comment posted by Alan on Sunday, May 26, 2013 12:45 PM
Thanks for this article! ASP.NET newbies like me really benefit from these kinds of well-written articles with code examples. I was pulling my hair out trying to get defaultfocus on my Web Content Page textboxes.
Thanks so much!