I want to display username in the top of all page.

Below is my code .

protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from Userman where Username =@username and Password=@password", con);
        cmd.Parameters.AddWithValue("@username", txtUsername.Text);
        cmd.Parameters.AddWithValue("@password", txtPassword.Text);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            Admin();
        }
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
        }
    }


    private void Admin()
    {
        if (txtUsername.Text == "admin" && txtPassword.Text == "123")
        {
            Response.Redirect("AdminHome.aspx");
        }
        else
        {
            Response.Redirect("UserHome.aspx");
        }
    }

Could you please help me on this

Dani AI

Generated

The OP () asked for the username displayed on every page. Replies from , , and point toward centralizing that UI in a master/shared layout. A reliable pattern is to authenticate once at login (set the auth cookie and optionally a short Session value) and have the master page read the authenticated principal (User.Identity.Name) — fall back to Session only if needed. Always HTML-encode the value before rendering to avoid XSS, and avoid duplicating the same lookup on every content page.

Example: after credentials are validated, set the principal and a session fallback.

// on successful credential check (pseudo)
Session["UserName"] = username;
System.Web.Security.FormsAuthentication.SetAuthCookie(username, false);
Response.Redirect("UserHome.aspx");

In the master page code-behind, read the principal or session and assign the label text (label must be runat="server"):

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string name = (User != null && User.Identity.IsAuthenticated)
            ? User.Identity.Name
            : Session["UserName"] as string;

        lblUserName.Text = string.IsNullOrEmpty(name) ? "" : HttpUtility.HtmlEncode(name);
        lblUserName.Visible = !string.IsNullOrEmpty(lblUserName.Text);
    }
}

Optional: expose a public property on the master so content pages can set or read the displayed name via a strongly typed Master reference.

Troubleshooting and security notes:

  • Use using() for SqlConnection/SqlCommand and avoid storing or transmitting plain passwords; store salted hashes (PBKDF2/BCrypt).
  • Prefer authentication primitives (FormsAuthentication / ASP.NET Identity) so User.Identity is populated site-wide.
  • Do not rely solely on Session for auth state; use secure, HttpOnly cookies and HTTPS.
  • If the label does not show, confirm the master page is applied, the label has runat="server" and the name is set before rendering.

Recommended Answers

All 4 Replies

You will need a bit more code..

Here is an idea, use a master page and place a label somewhere on the page. In the master page's code behind, page load, check to see if your user has been authenticated. You can do this by storing some information in a cookie or session variable. At the page load, if you find the information, fill in the text of that label. If it's not, redirect the user to the login page

Asp.net has quite a bit of classes and controls already ready for you. I'd recommend you go to asp.net and read up on some of their tutorials especially in the authentication section/chapter. It could save you a lot of time.

As our above said, put a Label on White in the place you want to stay, and check if authentication was performed Login if Yes complete the Label with the value of the User Name, if not let the Blank Label. display or change the style to None.

You can use shared folder - _mainLayout so that username will display in top of all pages.

follow below steps
1) use master page
2) add a label for showing username
3) after login save the username in session
4) Assign session value to the label in which you need to show username

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.