Display Logged in user details in TextBox in ASP.Net

Last Reply 5 months ago By pandeyism

Posted 5 months ago

I am trying to log in with a user name and password which is stored on a sql database. I would then take the information associated with that user (id, name, date of birth etc) and place it on a form (ASP). Please help me. Im using asp codes. I dont know where to start but i do have the table built with data.

Posted 5 months ago
Hi @JND,
Please try the following

How to get logedin user details after valid login using form authentication in ASP.Net

It might help you.

Cheers Andrea.

Posted 5 months ago

Hi JND,

Plese take reference the below code and correct your code.

HTML

CS.aspx

UserName :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<br />
Password :
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="Login" />

Default.aspx

ID :
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
Name :
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
DOB :
<asp:TextBox ID="txtBirth" runat="server"></asp:TextBox>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Code

CS.aspx.cs

protected void Login(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT UserName FROM [User] WHERE UserName = @UserName AND Password = @Password", con))
        {
            con.Open();
            cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
            cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
            string userName = Convert.ToString(cmd.ExecuteScalar());
            con.Close();
            Response.Redirect("Default.aspx?UserName=" + userName);
        }
    }
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["UserName"]))
    {
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT ID,FirstName + ' ' + LastName 'Name',BirthDay FROM [User] WHERE UserName = @UserName", con))
            {
                cmd.Parameters.AddWithValue("@UserName", Request.QueryString["UserName"]);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    txtID.Text = dr["ID"].ToString();
                    txtName.Text = dr["Name"].ToString();
                    txtBirth.Text = dr["BirthDay"].ToString();
                }
                con.Close();
            }
        }
    }
}

Screenshot