Search code examples
asp.netvb.netfindcontrolloginview

Setting focus to the User Name TextBox field of an ASP.Net LoginView


Using this ASP.Net LoginView, we would like to set focus on the User Name TextBox when it's loaded on the web page:

<asp:LoginView 
    ID="loginViewMain" 
    runat="server">

    <LoggedInTemplate>
        <asp:LoginName 
            ID="loginName" 
            runat="server"
            FormatString="Hello, {0}!<br/><br/> You have successfully<br/> logged onto the staff site." />

        <br/>
        <br/>

        (<asp:LoginStatus ID="loginStatus" runat="server" />)

        <br/>
        <br/>

    </LoggedInTemplate>

    <AnonymousTemplate>
        <asp:LoginStatus 
            ID="loginStatus" 
            runat="server" />
    </AnonymousTemplate>
</asp:LoginView>

This is the code-behind we tried to use to get focus on the User Name TextBox:

Private Sub loginViewMain_Load(sender As Object, e As EventArgs) Handles loginViewMain.Load

    Dim objContentPlaceHolder As ContentPlaceHolder
    Dim objLoginView As LoginView
    Dim objUserName As TextBox

    objContentPlaceHolder = CType(Me.FindControl("ContentPlaceHolderBody"), ContentPlaceHolder)

    If Not objContentPlaceHolder Is Nothing Then

        objLoginView = CType(objContentPlaceHolder.FindControl("loginViewMain"), LoginView)

        If Not objLoginView Is Nothing Then
            objUserName = objLoginView.FindControl("UserName")
            objUserName.Focus()
        End If
    End If
End Sub

Execution does get into this If structure:

If Not objLoginView Is Nothing Then

Can you tell me what else I need to add in the If structure of this coding to get hold of the User Name TextBox?


Solution

  • You can do that without the need to know the details of the LoginView control. Instead use JavaScript to find the first textbox and focus on it.

    Add the following code in your code behind file:

    var script = string.Format(@"
        var inputs = document.getElementById('{0}').getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {{
            var inp = inputs[i];
            if (inp.type.toUpperCase() !== 'TEXT') continue;
            inp.focus();
            inp.select();
            break;
        }}", this.LoginView.ClientID);
    
    // register the script
    ScriptManager.RegisterStartupScript(this, this.GetType(), "login focus", script, true);
    

    or in VB.NET:

    Dim script = String.Format(
        "var inputs = document.getElementById('{0}').getElementsByTagName('input');" &
        "for (var i = 0; i < inputs.length; i++) {{" &
        "    var inp = inputs[i];" & 
        "    if (inp.type.toUpperCase() !== 'TEXT') continue;" & 
        "    inp.focus();" & 
        "    inp.select();" &
        "    break;" & 
        "}}", Me.LoginView.ClientID)
    
    ' register the script
    ScriptManager.RegisterStartupScript(Me, TypeOf(this), "login focus", script, True)