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. 

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

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