Link to home
Start Free TrialLog in
Avatar of Starr Duskk
Starr DuskkFlag for United States of America

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!


Avatar of samtran0331
samtran0331
Flag of United States of America image

Bob,
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...
<%@ Page Language="VB" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
 
    Protected Sub Login1_LoggingIn(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LoginCancelEventArgs)
        Dim lctrl As Login
        lctrl = CType(LoginView1.FindControl("Login1"), Login)
        
        Dim chk As CheckBox = CType(lctrl.FindControl("RememberMe"), CheckBox)
        If chk.Checked Then
            Response.Write("Forget Me Not.")
        Else
            Response.Write("Forget Me.")
        End If
    End Sub
 
    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)
 
    End Sub
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lctrl As Login
        lctrl = CType(LoginView1.FindControl("Login1"), Login)
        Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)
        tb.Focus()
    End Sub
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LoginView ID="LoginView1" runat="server">
        <LoggedInTemplate>Logged in
        <asp:Login ID="Login1" runat="server" OnLoggingIn="Login1_LoggingIn" OnAuthenticate="Login1_Authenticate">
            <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>
        
        </LoggedInTemplate>
        <AnonymousTemplate>
        
        </AnonymousTemplate>
        </asp:LoginView>
    </div>
    </form>
</body>
</html>

Open in new window

Avatar of Starr Duskk

ASKER

If I copy and paste your entire solution into a page by itself with no codebehind, it gives this error:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)

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:TextBox>


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.IsAuthenticated = True Then
            Dim lctrl As Login
            lctrl = CType(LoginView1.FindControl("Login1"), Login)
            Dim tb As TextBox = CType(lctrl.FindControl("UserName"), 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.IsAuthenticated = False Then
            Dim lctrl As Login
            lctrl = CType(LoginView1.FindControl("Login1"), Login)
            Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)
            tb.Focus()
        End If
    End Sub
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??
ASKER CERTIFIED SOLUTION
Avatar of samtran0331
samtran0331
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.

<%@ 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>

Open in new window

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("UserName"), 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?

>>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('TextBox1');// -->
</script>
Using:
            Dim lctrl As Login
            lctrl = CType(LoginView1.FindControl("Login1"), Login)
            Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)
            tb.Focus()


the rendered html is:
<script type="text/javascript">
<!--
WebForm_AutoFocus('ctl00_ContentPlaceHolder1_LoginView1_Login1_UserName');// -->
</script>



which should work (same MS function), but doesn't.


Using the js function I put in,
            Dim lctrl As Login
            lctrl = CType(LoginView1.FindControl("Login1"), Login)
            Dim tb As TextBox = CType(lctrl.FindControl("UserName"), TextBox)
            'tb.Focus()
            SetControlFocus(tb)

renders:
<script language='JavaScript'>
<!--
function SetFocus()
{
      document.aspnetForm['ctl00$ContentPlaceHolder1$LoginView1$Login1$UserName'].focus();
}
window.onload = SetFocus;
// -->
</script>


which is working for me...
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.
oh duh. You have

If User.Identity.IsAuthenticated = True Then

and since I switched it, I need:

If Not User.Identity.IsAuthenticated = True Then
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.


I will ask about the Page_Load not working with Masterpages in a different post.

thanks for your help!
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"
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.IsAuthenticated = True Then

            ' below code sets the focus to the first field in the control
            'LoginView1.FindControl("Login1").Focus()

            ' use the below to find the UserName and set focus on a specific field by name...
            Dim lctrl As Login
            lctrl = CType(LoginView1.FindControl("Login1"), Login)
            '' below code sets the focus on the UserName field...
            'lctrl.FindControl("UserName").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("UserName"), TextBox)
            FormUtility.SetFocusControl(tb)

        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.