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

ASP.NET server-side focus control

2.38/5 (5 votes)
26 Jun 2006CPOL 1   77  
The user can easily set focus on a web control when the page loads or after an event is fired.

Introduction

I created this component to enable users to set focus on the client-side more easily. The implementation for this component is easy. JavaScript coding is not required.

How to add and run the component

You just need to provide the control ID to the function setFocus. The application will automatically generate JavaScript and set the focus to txtUserName. By default, the form ID is "Form1".

C#
protected System.Web.UI.WebControls.TextBox txtUserName;
protected System.Web.UI.WebControls.TextBox txtPassword;

When the Page Loads

C#
private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    if(!Page.IsPostBack)
    {
        WebControlFocus1.setFocus(txtUserName.ID);
    }
}

If the form ID is not the default "Form1", for example, if the form ID is "myForm", change it in the code as below:

C#
private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    if(!Page.IsPostBack)
    {
        WebControlFocus1.setFocus(txtUserName.ID,"myForm");
    }
}

When the button is clicked, the user can set the focus on txtPassword like:

C#
private void btnSubmit_Click(object sender, System.EventArgs e){if(InputValidation())
{
    WebControlFocus1.setFocus(txtPassword.ID);
}

This component was developed for ASP.NET 1.1.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)