Subscribe

RSS Feed (xml)

Programmatically Set Control Focus

The ASP.NET Web controls don't provide any way to programmatically set control focus. They do provide a TabIndex property that allows you to set the tab order, but this property applies only to Microsoft Internet Explorer and can't be used to programmatically set the focus to the control of your choice. To overcome this limitation, you need to add a little snippet of JavaScript code.


The following subroutine generalizes this task. It accepts a reference to any control object, retrieves the associated client ID (which is the ID that the JavaScript code must use to refer to the control), and then builds and registers the startup script for setting the focus.



private void SetFocus(Control ctrl) {

// Define a JavaScript statement that will move focus to
// the desired control.
string setFocus = "<script language='javascript'>" +
"document.getElementById('" + ctrl.ClientID +
"').focus();</script>";

// Add the JavaScript code to the page.
this.RegisterStartupScript("SetFocus", setFocus);
}

If you add this subroutine to a Web form, you can call SetFocus as needed. Here's an example that sets the focus when the page first loads:




private void Page_Load(object sender,
System.EventArgs e) {

if (!this.IsPostBack) {
// Move to a specific text box the first time the page loads.
SetFocus(TextBox1);
}
}



Technorati :

No comments:

Variety in the Web World