Get UserId on page load after login in ASP.Net

Last Reply 11 months ago By dharmendr

Posted 11 months ago

Please How do I fetch UserID on page after login, I have asked this alot of times yet no solution. 

Results 1 - 5 of 9 12
Posted 11 months ago Modified on 11 months ago

Hi micah,

I have created sample code which fullfill requirement.

HTML

<div>
    UserName:<asp:TextBox ID="txtUserName" runat="server" />
    <br />
    <br />
    Password:<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
</div>
<div>
    <br />
    <br />
    <asp:Label ID="lblUserId" Text="" runat="server" />
    <asp:Label ID="lblUserName" Text="" runat="server" />
</div>

C#

private string constr = ConfigurationManager.ConnectionStrings["constr"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {

    }

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username='" + txtUserName.Text + "'And password='" + txtpassword.Text + "'", con))
        {
            DataTable dt = new DataTable();
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                sda.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                   Session["UserId"] = dt.Rows[0]["Username"].ToString();
                   Response.Redirect("~/Default2.aspx");
                }
            }
        }
    }
}

Second Page

HTML

<div>
    UserId:<asp:Label ID="lblUserId" Text="" runat="server" />
</div>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        lblUserId.Text = Session["UserId"].ToString();
    }
}

Screenshot


Posted 11 months ago

This solution is not addressing my question as well, if I login with username and password but I will pass the Userid to the landing page and then fetch it on the new page


Posted 11 months ago

Hi micah,

Modified the code.Please recheck


Posted 11 months ago

Will session work with Asp.Net web form authentication?,  because that what you used and Am told it doesn't.


Posted 11 months ago

Instead of Session["UserId"] use HttpContext.Current.Session["UserId"]. It will work.

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html