Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Jul 9, 2002

Moving the focus on a control when the page loads

ASP.NET doesn't provide a built-in method for giving a control the input focus when the page loads. In fact, you can assign the TabIndex properties to controls on a page, but you can't use this property to set the initial focus on a control of your choice.

The following procedure provides you with the ability to do exactly this


Sub SetControlFocus(ByVal ctrl As Control)
    Dim code As String = String.Format("<script language='javascript'>" & _
        "document.getElementById(""{0}"").focus();</script>", ctrl.ClientID)
    ctrl.Page.RegisterStartupScript("SetControlFocus", code)
End Sub
As you see, the procedure inserts a line of JavaScript that runs after the page has been loaded, and that gives the focus to the control you pass as an argument. Because the Page object is retrieved as a property of the control, you can store this routine in any module of your ASP.NET application. You typicall call this procedure from the Page_Load event:

Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles _
    MyBase.Load
    SetControlFocus( TextBox2 )
End Sub
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date