Wednesday, 20 July 2011

Set Focus on Controls with ASP.NET 4.0 and C#


This tutorial will demonstrate how to give a control focus when the page is loaded using ASP.NET 4.0 and C#.

Setting a Control's Focus
To demonstrate how to give a specific control focus when a page is loaded, we will create a simple web site with a textbox on it. 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.
We used over 10 web hosting companies before we found Server Intellect. Our cloud hosting,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

Now that we have a simple form setup, we need to add some code that will set the focus to the textbox we added. To do this, open up Default.aspx.cs for editing and add in the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    //give the textbox focus
    TextBox1.Focus();
}

Now when your page is loaded, the textbox will have focus so you will be able to start typing in it immediately without having to click on it.

Focusable Controls
We have demonstrated how easy it is to a give a control focus using ASP.NET and C#. However, the catch is that only certain controls can actually have focus. These controls are as follows:
  • Button
  • LinkButton
  • ImageButton
  • CheckBox
  • DropDownList
  • FileUpload
  • HyperLink
  • ListBox
  • RadioButton
  • TextBox
If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

Giving focus to a control can be an easy way to indicate to the user where to begin when filling out forms on your web site.

No comments:

Post a Comment