Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do you initially set focus to a control on an ASP.NET web page?

ASP.NET 101

how do you initially set focus to a control on an ASP.NET web page?

by  JScannell  Posted    (Edited  )
Have you ever wanted to set initial focus to a specific control on a web form? I have! And it took me a lot of digging around to come up with the solution.

In my case, I have a master page and a content page. I need to set the initial focus to a text box named 'lkpLoginname'. here's my code that gets placed in the Page_Load event of the content page (note that you don't want to do this on postbacks):

If IsPostBack then Exit Sub

'
' Initial entry. Set focus to the windows ID text box
'
pnlEditEmps.Focus()

Dim mainform As HtmlForm = DirectCast ( Master.FindControl ( "Form1" ), HtmlForm )
Dim username As TextBox = DirectCast ( pnlEditEmps.FindControl ( "lkpLoginName" ), TextBox )

If mainform IsNot Nothing AndAlso username IsNot Nothing Then
mainform.DefaultFocus = username.UniqueID
End If

The master page has a <form> and content page is wrapped with a panel.

If you don't have a master page, then you need a form element on your web page with a panel wrapped around it. I was able to do this on a popup window and the code that worked is as follows:

If IsPostBack then Exit Sub

'
' Initial entry. Set focus to the windows ID text box
'
Dim mainform As HtmlForm = DirectCast ( pnlWrapForm.FindControl ( "Form1" ), HtmlForm )
Dim username As TextBox = DirectCast ( pnlWrapForm.FindControl ( "lkpLoginName" ), TextBox )
If mainform IsNot Nothing AndAlso username IsNot Nothing Then
mainform.DefaultFocus = username.UniqueID
End If


Sincerely yours,
Jerry Scannell

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top