Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Focusing on TextBoxes


Focusing on TextBoxes

From an end-user’s perspective, one of the most annoying aspects of ASP.NET applications is that the majority of them don’t give the input focus to any textboxes in the page. Imagine a page designed to collect some input data—say, a form to fill out. This page inevitably contains a suite of textbox controls. Wouldn’t it be nice if the page could show up with the input focus already set to the first (or any other) textbox? This saves you one click, but more importantly, it would allow users to start typing as soon as the page displays. They could do the job without using the mouse, which, in the case of relatively inexpert users, marks the difference between productive users and just users.

Probably many ASP.NET applications don’t do this because ASP.NET 1.x doesn’t provide a method or a property that does it quickly and efficiently. This feature will be introduced in ASP.NET 2.0 under the form of a SetFocus method added to the Page class. The method takes the ID of the control to give the focus and injects some script code on purpose. Let’s see how to achieve this same functionality in ASP.NET 1.x.

The problem is small in the markup code and script you need to write. The rub consists in finding out a programming interface that makes the ID of the HTML element definable through server-side code.

The Page class exposes a few methods to register script code and make it run at certain moments in the page’s lifecycle. For example, the RegisterStartupScript method takes the specified string of Javascript code and adds it to an internal hashtable for further use.

RegisterStartupScript("SetFocusSnippet", code)

The first parameter to the method indicates the key with which the Javascript code is cached. Here’s a possible Javascript code snippet to set the focus to a particular form control:

<script language=javascript>
function setFocus(ctl) {
   if (document.forms[0][ctl] != null)
      document.forms[0][ctl].focus();
}
setFocus(nameOfTheControl)
</script>

The name of the control is the actual parameter of the SetFocus function. Because ASP.NET pages normally have just one form, the index of 0 makes sense. If you’re having more forms (note that only one can be visible at a time), replace the index with the unique ID of the desired form. The <script> block above is made of two parts—the function declaration and the function call. Your page will build a string like that and replace nameOfTheControl with the actual ID of the control to give focus to.

When you register script code through RegisterStartupScript, then any runnable code in the code runs when encountered. ASP.NET inserts the <script> block just before the closing tag of the form </form>. This means that first the form is completely initialized and then the script is run—sort of startup code. The following code shows what you need to add to your ASP.NET page to be able to give focus to a particular textbox upon loading:

<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
   if (!IsPostBack)
     SetFocus("user");
}

private void SetFocus(string ctlName)
{
   // Build the Javascript string
   string code = BuildJavascript(ctlName);
   RegisterStartupScript("MyCode", code);
}
</script>

You should avoid registering the same piece of code more than once. To avoid this, check the script for existence using the IsStartupScriptRegistered function before you call RegisterStartupScript.


Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant based in Rome, Italy. Dino is a contributing editor to Windows Developer Network and MSDN Magazine, and the author of several books for Microsoft Press including Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET. Contact Dino at [email protected].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.