Set focus to a textbox on page load

W

Water Cooler v2

I am new to ASP/ASP.NET so kindly be gentle. When my index.aspx page
loads, I need the focus to be on one of the textboxes called
txtUserName.

I come from a VB background, so expecting the obvious, I go to the
Page_Load event of the index.aspx page and try to write
txtUserName.SetFocus but I see there isn't a SetFocus method for the
System.Web.UI.WebControls.TextBox class.

What's the way to set the focus to a textbox on the page load in
ASP.NET?
 
G

Guest

you can write a function something like this and use it when u need them.

protected void SetFocus(Control controlToFocus){
string formName = GetFormName(controlToFocus);
string jsString="<script language=javascript>document." + formName +
".elements['" + controlToFocus.UniqueID + "'].focus();</script>";
if(Page.IsStartupScriptRegistered("SetFocusToSearch")==false)
Page.RegisterStartupScript("SetFocusToSearch",jsString);

Hope this helps.
--
Kannan.V
Home : http://www.kannanv.com
Blog : http://kannanv.blogspot.com
Web : http://www.DotnetLounge.net

"Any one who has never made a mistake has never tried anything new" - Einstein
 
P

Patrick Olurotimi Ige

As the last post adviced this should do the trick:-

Private Sub SetFocus(ByVal ctrl As Control)
' Define the JavaScript function for the specified control.
Dim focusScript As String = "<script language='javascript'>" & _
"document.getElementById('" + ctrl.ClientID & _
"').focus();</script>"

' Add the JavaScript code to the page.
Page.RegisterStartupScript("FocusScript", focusScript)
End Sub

Hope this helps
Patrick
 
E

Eliyahu Goldin

It's a client-side task. You need to call javascript focus() method on the
element you want to set focus on.

Eliyahu
 
Joined
Jan 13, 2011
Messages
1
Reaction score
0
focus

just add into the Page-Load function the following:

txUserName.Focus();

works for me.. cheers!



Water Cooler v2 said:
I am new to ASP/ASP.NET so kindly be gentle. When my index.aspx page
loads, I need the focus to be on one of the textboxes called
txtUserName.

I come from a VB background, so expecting the obvious, I go to the
Page_Load event of the index.aspx page and try to write
txtUserName.SetFocus but I see there isn't a SetFocus method for the
System.Web.UI.WebControls.TextBox class.

What's the way to set the focus to a textbox on the page load in
ASP.NET?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top