Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Using a TabIndex with a UserControl containing .NET controls

3.05/5 (9 votes)
11 Mar 20071 min read 1   619  
An article to demonstrate how to create a TabIndex for a user control in ASP .NET and the controls contained within the user control.

Usercontrol TabIndex

Introduction

It's not uncommon to have a user control which acts as a simple container for a number of "sub controls". A typical example might be an Address control containing an Address, City, and Country textbox. This "Address" user control does not have a TabIndex property by definition. However, the user might wish to tab smoothly through their page (including through the controls contained within the user control).

What we can do though is create a TabIndex property for the user control and ensure that when it receives focus, the controls within it will tab through successfully.

Using the code

The first bit is to create a TabIndex property for the user control. In fact, what we do is set the TabIndex of the first control (the Address control), then the City control, and finally the Country control.

C#
private short _tabIndex;
public short TabIndex
{
    get
    {
        return _tabIndex;
    }
    set
    {
        _tabIndex = value;
        txtAddress.TabIndex = (short)(value++);
        txtCity.TabIndex = (short)(value++);
        txtCountry.TabIndex = (short)(value);
    }
}        

Implementation

When writing your HTML, simply set the TabIndex of each of control on your page. However, you need to allow for each of the controls within your user control. So in this example, the user control will use TabIndexes 2, 3, and 4. Thus, you need to restart the TabIndex at 5 for the next control on the page.

However, it may be worth allowing for additional controls (in case you choose to add, for example, a Postal Code textbox further down the line). So in this case, you could restart the TabIndex at 12 (rather than 5), allowing for up to 10 controls in total.

HTML
<asp:TextBox ID="txtName" runat="server" TabIndex="1"></asp:TextBox>

<uc1:Address ID="ctlAddress" runat="server" TabIndex="2"/>

<asp:TextBox ID="txtComments" runat="server" TabIndex="5"></asp:TextBox>

Points of interest

Note that the property TabIndex is a short, so when we set the TabIndex of the controls within the user control we must cast the value as a short.

History

  • 07 March 2007 - Version 1.0.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here