Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

How to set the focus on an asp.net server control

It is a very common request when designing an asp.net application, to set the focus on an asp.net control.

We can set the focus on an asp.net control

  • dynamically
  • declaratively

Some of the most common asp.net server controls we can set the focus on are:

  • TextBox
  • ListBox
  • RadioButton
  • CheckBox
  • Hyperlink

Let's create an asp.net application with Visual studio

1) We fire the Visual Studio 2008-2010

2) We create an asp.net web site, from the available templates

3) We choose C# as a programming language

4) We drag and drop on the empty default.aspx the following controls

  • TextBox
  • HyperLink
  • Button

5) Leave the default names ( Button1, Hyperlink1, TextBox1 )

6) If we want to set the focus on the Hyperlink control

7) In the Page_Load event handler routine we can type the following

protected void Page_Load(object sender, EventArgs e)
    {
        if (HyperLink1 != null) HyperLink1.Focus();
    }

8) So we just use the Focus method of the Hyperlink control


9) We can also set the focus on a web server control, by using the SetFocus() method of the Page control, by passing as a parameter in the SetFocus() method, the control ID.

This is how we transform the code snippet above

protected void Page_Load(object sender, EventArgs e)
    {
        if (HyperLink1 != null) Page.SetFocus(HyperLink1);
    }

10 ) Another way to set the focus on a control (TextBox1) is to do so declaratively. In the default.aspx page we can write in the form tag

<form id="form1" runat="server" defaultfocus="TextBox1">

11) Now we can add another page, Validation.aspx , and this can be a page where, someone can log in to our web site. have a look at the screenshot below. We have textboxes, radio buttons and a button.

 

12) We also add RequiredFieldValidator controls on the page and we associate them with the controls.

13) So if the validation fails, the focus will be set on the control that failed in the validation process ( e.g email ).

14) Have a look at the code below. The important property to look for is SetFocusOnError="true"

 

<asp:requiredfieldvalidator id="_firstNameValidator" runat="server" width="100%" InitialValue="" ErrorMessage="First name must be filled in." SetFocusOnError="true"
                            Display="Dynamic" ControlToValidate="_firstname" ValidationGroup="SignUp"><img id="Img1" runat="server" enableviewstate="False" src='~/images/oops.jpg' />
 

Important Note:In order for the set focus on the controls to operate as above , the client side scripting on the browsers must be enabled.

If you need the source code, please email me at "info@nksolutions.gr"

Hope it helps!!!

Comments

Andy said:

I learnt so much from this post.

# September 26, 2010 2:27 PM