Starr Duskk
asked on
asp.net 2.0 setting field focus
I was trying to find out how to set field focus in asp.net 2.0.
I searched and found this post:
https://www.experts-exchange.com/questions/21669918/ASP-NET-Setting-focus-to-a-field.html?sfQueryTermInfo=1+asp.net+field+focu
Which takes to this blog:
http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
However, I wasn't sure that article wasn't referring to asp.net 1.0 due to the discussion of the problems with smartnavigation and this solution and also what is says on 4guys about 2.0 having scroll position built-in.
http://aspnet.4guysfromrolla.com/articles/111704-1.aspx
Is there a way in 2.0 to set focus on form field, such as the Log in control User Name? and if so, how to implement it?
thanks!
I searched and found this post:
https://www.experts-exchange.com/questions/21669918/ASP-NET-Setting-focus-to-a-field.html?sfQueryTermInfo=1+asp.net+field+focu
Which takes to this blog:
http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
However, I wasn't sure that article wasn't referring to asp.net 1.0 due to the discussion of the problems with smartnavigation and this solution and also what is says on 4guys about 2.0 having scroll position built-in.
http://aspnet.4guysfromrolla.com/articles/111704-1.aspx
Is there a way in 2.0 to set focus on form field, such as the Log in control User Name? and if so, how to implement it?
thanks!
ASKER
If I copy and paste your entire solution into a page by itself with no codebehind, it gives this error:
Exception Details: System.NullReferenceExcept ion: Object reference not set to an instance of an object.
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
If I add the function by itself in my existing code behind, it doesn't error, but it also doesn't set focus..
???
Exception Details: System.NullReferenceExcept
Dim tb As TextBox = CType(lctrl.FindControl("U
If I add the function by itself in my existing code behind, it doesn't error, but it also doesn't set focus..
???
That's odd...I tested it before I posted it...and you can see the textbox is on the page...
<asp:TextBox ID="UserName" runat="server"></asp:TextB ox>
I bet what's happening is that, in my example, the LoggedIn template is showing by default, and in yours, the anonymous template is showing (mine is flipflopped from reality because I was too lazy to really set up auth)
would need to actually check whether user is logged in or not...maybe:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If User.Identity.IsAuthentica ted = True Then
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr ol("Login1 "), Login)
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
tb.Focus()
End If
End Sub
or for a real app:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If User.Identity.IsAuthentica ted = False Then
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr ol("Login1 "), Login)
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
tb.Focus()
End If
End Sub
<asp:TextBox ID="UserName" runat="server"></asp:TextB
I bet what's happening is that, in my example, the LoggedIn template is showing by default, and in yours, the anonymous template is showing (mine is flipflopped from reality because I was too lazy to really set up auth)
would need to actually check whether user is logged in or not...maybe:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If User.Identity.IsAuthentica
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr
Dim tb As TextBox = CType(lctrl.FindControl("U
tb.Focus()
End If
End Sub
or for a real app:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If User.Identity.IsAuthentica
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr
Dim tb As TextBox = CType(lctrl.FindControl("U
tb.Focus()
End If
End Sub
ASKER
yes, your original code had the Login control within the logged in template, the anonymous template was blank.
Swapping that around stopped the error and allowed the focus to the field.
However, if I create an entirely new page using codebehind and a master page, and put the working example into it, it no longer sets the focus. But it doesn't error. It just doesn't set focus??
Swapping that around stopped the error and allowed the focus to the field.
However, if I create an entirely new page using codebehind and a master page, and put the working example into it, it no longer sets the focus. But it doesn't error. It just doesn't set focus??
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yours worked?
Because aside from the onloggingin and onauthenticate functions needing to be removed... and the anonymousview and loggedin views being backwards again, I set up mine like yours and it doesn't set focus.
sigh.
Because aside from the onloggingin and onauthenticate functions needing to be removed... and the anonymousview and loggedin views being backwards again, I set up mine like yours and it doesn't set focus.
sigh.
<%@ Page Language="VB" MasterPageFile="~/site1.master" Title="Untitled Page" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If User.Identity.IsAuthenticated = True Then
Dim lctrl As Login
lctrl = CType(LoginView1.FindControl("Login1"), Login)
Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)
'MS function won't work
'tb.Focus()
'Use custom JS
SetControlFocus(tb)
End If
End Sub
Public Shared Sub SetControlFocus(ByVal control As Control)
Dim sb As StringBuilder = New StringBuilder
With sb
.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "<script language='JavaScript'>" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<!--" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("function SetFocus()" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("{" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("" & Microsoft.VisualBasic.Chr(9) & "document.")
Dim p As Control = control.Parent
While Not (TypeOf p Is System.Web.UI.HtmlControls.HtmlForm)
p = p.Parent
End While
.Append(p.ClientID)
.Append("['")
.Append(control.UniqueID)
.Append("'].focus();" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("}" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("window.onload = SetFocus;" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("// -->" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<" & "/script>")
End With
control.Page.ClientScript.RegisterClientScriptBlock(control.GetType, "SetFocus", sb.ToString)
End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
Logged in
</LoggedInTemplate>
<AnonymousTemplate>
<asp:Login ID="Login1" runat="server" >
<LayoutTemplate>
<table border="0" cellpadding="1" cellspacing="0" style="border-collapse: collapse">
<tr>
<td>
<table border="0" cellpadding="0">
<tr>
<td align="center" colspan="2">
Log In</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label></td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color: red">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
</AnonymousTemplate>
</asp:LoginView>
</div>
</asp:Content>
ASKER
I was reading this scott guthrie blog:
http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx#520107
and it says you can use Page.Form.DefaultButton and elsewhere it talks about Page.Form.DefaultFocus with a master page....
I tried both of these in the page load, and neither work...
Page.Form.DefaultFocus = "UserName"
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
Page.Form.DefaultFocus = tb
Scott says...
From within your content page you should be able to write code like this to set the default button:
Maybe that's heading in the right direction?
http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx#520107
and it says you can use Page.Form.DefaultButton and elsewhere it talks about Page.Form.DefaultFocus with a master page....
I tried both of these in the page load, and neither work...
Page.Form.DefaultFocus = "UserName"
Dim tb As TextBox = CType(lctrl.FindControl("U
Page.Form.DefaultFocus = tb
Scott says...
From within your content page you should be able to write code like this to set the default button:
Maybe that's heading in the right direction?
>>Yours worked?
>>Because aside from the onloggingin and onauthenticate functions needing to be removed... and the
>>anonymousview and loggedin views being backwards again, I set up mine like yours and it doesn't
>>set focus.
Yes, to try an keep the post shorter, I removed the functions w/o removing the attributes on the form...
>>Scott says...
>>From within your content page you should be able to write code like this to set the default button:
>>Maybe that's heading in the right direction?
I'm afraid that you'd get the same result, whether using the form's defaultbutton or a textbox's "focus", what happens is .Net will write its own Javascript to the page like the below:
<script type="text/javascript">
<!--
WebForm_AutoFocus('TextBox 1');// -->
</script>
>>Because aside from the onloggingin and onauthenticate functions needing to be removed... and the
>>anonymousview and loggedin views being backwards again, I set up mine like yours and it doesn't
>>set focus.
Yes, to try an keep the post shorter, I removed the functions w/o removing the attributes on the form...
>>Scott says...
>>From within your content page you should be able to write code like this to set the default button:
>>Maybe that's heading in the right direction?
I'm afraid that you'd get the same result, whether using the form's defaultbutton or a textbox's "focus", what happens is .Net will write its own Javascript to the page like the below:
<script type="text/javascript">
<!--
WebForm_AutoFocus('TextBox
</script>
Using:
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr ol("Login1 "), Login)
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
tb.Focus()
the rendered html is:
<script type="text/javascript">
<!--
WebForm_AutoFocus('ctl00_C ontentPlac eHolder1_L oginView1_ Login1_Use rName');// -->
</script>
which should work (same MS function), but doesn't.
Using the js function I put in,
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr ol("Login1 "), Login)
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
'tb.Focus()
SetControlFocus(tb)
renders:
<script language='JavaScript'>
<!--
function SetFocus()
{
document.aspnetForm['ctl00 $ContentPl aceHolder1 $LoginView 1$Login1$U serName']. focus();
}
window.onload = SetFocus;
// -->
</script>
which is working for me...
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr
Dim tb As TextBox = CType(lctrl.FindControl("U
tb.Focus()
the rendered html is:
<script type="text/javascript">
<!--
WebForm_AutoFocus('ctl00_C
</script>
which should work (same MS function), but doesn't.
Using the js function I put in,
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr
Dim tb As TextBox = CType(lctrl.FindControl("U
'tb.Focus()
SetControlFocus(tb)
renders:
<script language='JavaScript'>
<!--
function SetFocus()
{
document.aspnetForm['ctl00
}
window.onload = SetFocus;
// -->
</script>
which is working for me...
ASKER
Can you paste in your working code in its entirety (without master page), because for brevity's sake is not making this any briefer. lol.
Are you running it with anonymous backwards and getting it to work? Mine just errors if I do that. Maybe "fixing" it is messing something up?
thanks.
Are you running it with anonymous backwards and getting it to work? Mine just errors if I do that. Maybe "fixing" it is messing something up?
thanks.
ASKER
oh duh. You have
If User.Identity.IsAuthentica ted = True Then
and since I switched it, I need:
If Not User.Identity.IsAuthentica ted = True Then
If User.Identity.IsAuthentica
and since I switched it, I need:
If Not User.Identity.IsAuthentica
ASKER
Okay,this works within the page.
But when I move the Page_Load to my codebehind, it never loads it. I'm doing a debug and stepping through and it doesn't hit it at all.
But when I move the Page_Load to my codebehind, it never loads it. I'm doing a debug and stepping through and it doesn't hit it at all.
ASKER
I will ask about the Page_Load not working with Masterpages in a different post.
thanks for your help!
thanks for your help!
ASKER
I figured out why Page_Load wasn't working with my Masterpages. I had:
AutoEventWireup="false"
I set it to true and it runs...
AutoEventWireup="true"
AutoEventWireup="false"
I set it to true and it runs...
AutoEventWireup="true"
ASKER
samtran,
I spoke with Mike Harder (from Microsoft) and he said this should work...
I was able to get it to work in IE6 and Firefox but not in IE7. He sent me sample code in C# and even that didn't work in my IE7 on page load. If I hit refresh, it did set focus most of the time, but not on initial page load and not consistently.
He said it works for his IE7, but not mine. I have no toolsbars or plugins other than OneNote.
Please let me know if the first or the second works for you... Maybe it's just my browser. I rebooted and still doesn't work.
Here's what I ended up with....
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not User.Identity.IsAuthentica ted = True Then
' below code sets the focus to the first field in the control
'LoginView1.FindControl("L ogin1").Fo cus()
' use the below to find the UserName and set focus on a specific field by name...
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr ol("Login1 "), Login)
'' below code sets the focus on the UserName field...
'lctrl.FindControl("UserNa me").Focus ()
' nkt: the above works consistently for IE6 and Firefox, but not IE 7
' for IE7 browsers to work consistently, custom write the javascript
' if IE7 has a future "fix" should be able to remove this and use the first function
Dim tb As TextBox = CType(lctrl.FindControl("U serName"), TextBox)
FormUtility.SetFocusContro l(tb)
End If
End Sub
I spoke with Mike Harder (from Microsoft) and he said this should work...
I was able to get it to work in IE6 and Firefox but not in IE7. He sent me sample code in C# and even that didn't work in my IE7 on page load. If I hit refresh, it did set focus most of the time, but not on initial page load and not consistently.
He said it works for his IE7, but not mine. I have no toolsbars or plugins other than OneNote.
Please let me know if the first or the second works for you... Maybe it's just my browser. I rebooted and still doesn't work.
Here's what I ended up with....
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not User.Identity.IsAuthentica
' below code sets the focus to the first field in the control
'LoginView1.FindControl("L
' use the below to find the UserName and set focus on a specific field by name...
Dim lctrl As Login
lctrl = CType(LoginView1.FindContr
'' below code sets the focus on the UserName field...
'lctrl.FindControl("UserNa
' nkt: the above works consistently for IE6 and Firefox, but not IE 7
' for IE7 browsers to work consistently, custom write the javascript
' if IE7 has a future "fix" should be able to remove this and use the first function
Dim tb As TextBox = CType(lctrl.FindControl("U
FormUtility.SetFocusContro
End If
End Sub
Yeah, I haven't had time to test it yet...but I'm still guessing that when you throw master pages into the equation, it might get screwy...will test and let you know.
You're using the login control inside the loginview right?
You'll have to do it the way we did it to get the RememberMe checkbox, once you get the UserName textbox, in ASP.Net 2.0, textboxes have a "focus" function...
relevant code is in the page_load...I'm using the same test page as the RememberMe question you had before...
Open in new window