Could not find control inside LoginView LoggedIn template

6.3k Views Asked by At

I tried to get the LoginName control inside LoginView LoggedIn template , despite several methods, the code still could not work.

I wished to change the default username to the customer name.

Here is the code:

 <asp:LoginView ID="LoginView1" runat="server">
   <LoggedInTemplate> 


                 Hello, <asp:LoginName ID="LoginName1" runat="server"></asp:LoginName>

                 <br /> 

                 <div style="text-align: right; margin-right: 5px "> 
                <asp:LoginStatus ID="LoginStatus1" runat="server" LogoutPageUrl="~/Home.aspx" Font-Underline="True" />
                </div></div>
        </LoggedInTemplate>


    </asp:LoginView> 

at the code behind :

 protected void Login1_LoggedIn(object sender, EventArgs e)
    {

        LoginName loginName = LoginView1.FindControl("LoginName1") as LoginName;
        Response.Write(loginName.ToString());  //for now I used Response.Write for testing purposes
    }
2

There are 2 best solutions below

3
Aghilas Yakoub On

Hello you can try with this code

LoginView1.LoggedInTemplate.FindControl("LoginName1") as LoginName;
0
Mazdak Shojaie On

Try this:

 <asp:LoginView ID="LoginView1" runat="server">
  <LoggedInTemplate> 
    <asp:Label runat="server" ID="lblUserName" Text="" />
    <br /> 
    <div style="text-align: right; margin-right: 5px "> 
    <asp:LoginStatus ID="LoginStatus1" runat="server" LogoutPageUrl="~/Home.aspx" Font-Underline="True" />
  </LoggedInTemplate>
</asp:LoginView> 

and in code behinde:

  if (!Page.IsPostBack)
    if (this.Page.User.Identity.IsAuthenticated)      
       (this.LoginView1.FindControl("lblUserName") as Label).Text = "Hello, " + this.Page.User.Identity.Name;