O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Programmatically Set Control Focus

Problem

You want to specify that a specific control 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 do not provide any way to programmatically set the focus. They do provide a TabIndex property that allows you to set the tab order, but this property only applies to Microsoft Internet Explorer and cannot 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required