Wednesday, 20 July 2011

Working with TabIndex in ASP.NET 4.0 Controls with C#


This tutorial will demonstrate how to use the tab index of ASP.NET 4.0 controls to make your web site more use friendly.

Creating a Sample Form
To demonstrate how to work with the tab index property, we will create a simple form with a few text boxes that will allow us to tab around in a specified order. At this point, I have created a new ASP.NET Empty Web Site. To begin:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a textbox onto the web form.
  8. Add 2 break lines.
  9. Drag and drop a textbox under the break lines.
  10. Add 2 break lines.
  11. Drag and drop a textbox under the break lines.
I just signed up at Server Intellect and couldn't be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.

Now that we have a simple form setup, we need to add in some simple code to set the focus to the first text box on our page. This will allow us to start tabbing through the controls on our page immediately without selecting other controls in your web browser. To do this, open Default.aspx.cs up for editing and add in the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    //set focus to the first textbox
    TextBox1.Focus();
}

Next, we can test this out to see what actually happens on the page when we hit tab. To do this:
  1. Load up the web site.
  2. Hit tab.
  3. Notice that your focus was changed to the second textbox.
  4. Hit tab.
  5. Notice that your focus was change to the third textbox
Your focus changes in a specific order that corresponds to the order in which the controls are added to the page because no tab index is specified for any of our text boxes.

Modifying the Tab Index
In certain scenarios, you may want to create a form that has a specified order in which the focus will be changed when the user hits the tab key. We have complete control over this using the TabIndex property of our controls. To change the tab order of our controls, open Default.aspx to design mode and:
  1. Select TextBox1.
  2. Change the TabIndex property to '1'.
  3. Select TextBox2.
  4. Change the TabIndex property to '3'.
  5. Select TextBox3.
  6. Change the TabIndex property to '2'.
Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results!

To test this out:
  1. Load up the web site.
  2. Hit tab.
  3. Notice that your focus was changed to the third textbox.
  4. Hit tab.
  5. Notice that your focus was changed to the second textbox.
Properly configuring the tab order of your controls can greatly help your users fill out forms quickly and easily.

No comments:

Post a Comment