Get UserId on page load after login in ASP.Net

micah
 
on Sep 19, 2016 03:15 AM
Sample_711778.zip
9552 Views

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

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Results 1 - 5 of 9
Indresh
 
on Sep 19, 2016 03:56 AM
on Sep 19, 2016 06:12 AM

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

micah
 
on Sep 19, 2016 05:55 AM

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

Indresh
 
on Sep 19, 2016 06:28 AM

Hi micah,

Modified the code.Please recheck

micah
 
on Sep 19, 2016 06:36 AM

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

Indresh
 
on Sep 19, 2016 06:41 AM

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

Results 1 - 5 of 9