7.6 Programmatically Set Control Focus


Problem

You need to specify the control that should be given focus when the page is rendered and sent to the user .

Solution

Create a JavaScript statement that sets the focus, and add it to the page using the Page.RegisterStartupScript method.

Discussion

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);     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net