简体   繁体   中英

Get and display data of logged in user in a c# application

I've made a Login/Sign Up application with C# using WPF and XAML. When a user logs in I'd like to display some of the info that they input into the Sign Up form but no matter what user logs in, it always displays the info of the last registered account. How can I get it to display data based on the currently logged in user? This is the code that I've been able to muster up so far.

This is the page where I want user information to be displayed (as textblocks)

public partial class User_Homepage : Page
    {
        string connectionString = @"Data Source=HP;Initial Catalog=User_SignUpDB;Integrated Security=True;";

        public User_Homepage()
        {
            InitializeComponent();

            SqlConnection sqlCon = new SqlConnection(connectionString);
            sqlCon.Open();

            string query = "SELECT * FROM tblSignUP";
            SqlCommand createCommand = new SqlCommand(query, sqlCon);
            createCommand.Parameters.Clear();
            SqlDataReader dr = createCommand.ExecuteReader();
            while (dr.Read())
            {
                nameTxt.Text = (dr["StudentName"].ToString());

            }

            sqlCon.Close();   
        }
    }

This is the code from User Login Page

private void UserSignInBtn_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection sqlCon = new SqlConnection(@"Data Source=HP;Initial Catalog=User_SignUpDB;Integrated Security=True;");

            try
            {
                if (sqlCon.State == ConnectionState.Closed)
                {
                    sqlCon.Open();
                    string query = "SELECT COUNT (1) FROM tblSignUP WHERE StudentName=@StudentName AND Password=@Password";
                    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                    sqlCmd.CommandType = CommandType.Text;
                    sqlCmd.Parameters.AddWithValue("@StudentName", tbID.Text);
                    sqlCmd.Parameters.AddWithValue("@Password", PB.Password);
                    int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
                    if (count == 1)
                    {

                        // Custom Message Box and Dim Effect
                        var jim = new Dim();

                        jim.Show();
                        this.Effect = new BlurEffect();

                        var lsmb = new Custom_MessageBoxes.LoginSuccessfulMsgBox();
                        lsmb.ShowDialog();

                        this.Effect = null;
                        jim.Close();

                        //Move to User Homepage
                        var User_Homepage = new User_Homepage();
                        NavigationService.Navigate(User_Homepage);
                    }
                    else
                    {
                       // Custom Message Box and Dim Effect 2
                        var him = new Dim();

                        him.Show();
                        this.Effect = new BlurEffect();

                        var rmdlgb = new ReturnMessageDialogueBox();
                        rmdlgb.ShowDialog();

                        this.Effect = null;
                        him.Close();

                    }
                }
            }
            catch(Exception ex)
            {

            }
            finally
            {
                sqlCon.Close();
            }
        }

This is the code from User Registration/Create New Account Page

using (SqlConnection sqlCon = new SqlConnection(connectionString))
                {
                    sqlCon.Open();
                    SqlCommand sqlCmd = new SqlCommand("UserAdd", sqlCon);
                    sqlCmd.CommandType = CommandType.StoredProcedure;                 
                    sqlCmd.Parameters.AddWithValue("@StudentName", tbStudentName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@SchoolName", tbSchoolName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@HouseName", tbHouseName.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Prog", tbProg.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@PhoneNumber", tbPhoneNumber.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", tbAddress.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Password", pbPassword.Password.Trim());
                    sqlCmd.ExecuteNonQuery();

                    var dim = new Dim();
                    dim.Show();
                    this.Effect = new BlurEffect();

                    var cmb = new Custom_MessageBoxes.RegistrationComplete();
                    cmb.ShowDialog();

                    this.Effect = null;
                    dim.Close();
                    Clear();
                }

And heres the SQL stored procedure that I used

USE [User_SignUpDB]
GO
/****** Object:  StoredProcedure [dbo].[UserAdd]    Script Date: 5/2/2019 5:46:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[UserAdd]
@StudentName varchar(50),
@SchoolName varchar(50),
@HouseName varchar(50),
@Prog varchar(50),
@PhoneNumber varchar(50),
@Address varchar(250),
@Password varchar(50)
AS
    INSERT INTO tblSignUp(StudentName,SchoolName,HouseName,Prog,PhoneNumber,Address,Password)
    VALUES (@StudentName,@SchoolName,@HouseName,@Prog,@PhoneNumber,@Address,@Password)

So ultimately, what I want to do is display StudentName, HouseName, and Prog in their respective textboxes, based on who is logged in.

Whenever a user log in you have the the tbID.Text, you can save this variable, and in the home page re use it like this "SELECT * FROM tblSignUP WHERE studentName LIKE tbID.Text" (ofc you cant do it exactly like this, you have to make the proper sql statement but thats the way you do it) you can basically use the same principle that you use in the user log in page. This will get you the user you have just logged in

According to your code, the database design has a lot of flaws. Firstly, you need an unique identifier to identify each individual.

As i understood, you're using the "StudentName" for logging in, which is a bad practice. What if you have duplicate names? Therefore you need another unique column labeled as "username" which you could refer when logging in.

So when you have changed your table structure, change the query too.

change ---> string query = "SELECT COUNT (1) FROM tblSignUP WHERE StudentName=@StudentName AND Password=@Password";
to ---> string query = "SELECT COUNT (1) FROM tblSignUP WHERE username=@Username AND Password=@Password";

In addition to that, in your home page, you have to be specific on what information to be queried from the DB. Currently it's ---> string query = "SELECT * FROM tblSignUP";
And it should be changed to --> string query = "SELECT * FROM tblSignUP WHERE username = @Username";

Your question is an exact duplicate of your previous post - which was closed. That is a big red flag to you - you need to understand why that happened. SO is pretty accommodating and a closed question means the community thinks you can do better.

So let's start. First, don't use addwithvalue . Just don't. To go along with that, don't be a lazy developer - something encouraged by methods/functions like addwithvalue.

Next, you have this:

        SqlCommand createCommand = new SqlCommand(query, sqlCon);
        createCommand.Parameters.Clear();

Why? You create a new SqlCommand object. Why do you need to clear the parameters? Start thinking about your code and stop blindly writing statements if you don't understand what they do. If you find code that you reuse, LEARN what it does, adapt it to your own goals.

Next, we see that you are getting the same questions that you did not really respond to with the prior thread. Your application needs to "remember" the details of user that logs in. And note that how a user logs in will differ between an existing user and a new user. You have 2 different code paths here but they ultimately need to do the same thing - grant access to the user and establish information in your app that allows it to function for that logged in user.

As an aside, no one reading your question knows your skill level, your goals, your development environment, or your work situation. A student learning a first language needs a different level of guidance then one with significant experience. A member of a development team needs another level (and should be asking team members first before posting). If you don't provide any clues (or tell us explicitly), the suggestions and comments may not make much sense. They might also seem condescending. Posting questions in public forum is not as easy as one might think. Learn to ask smart questions that encourage others to help.

So what "information" does your app require after a successful login? You tell us. I will guess that it needs some (perhaps all) of the information involved in the registration logic. You might also need the primary key for that row in the table. What is the primary key and how do you get it? You tell us. I'm guessing that the actual primary key value(s) of the user will be needed in other parts of your application. Based on the login code, username seems to be the natural key (which I hope is enforced with the proper constraint) but the actual primary key might be a different column(s).

Now you might think that you can simply save the username some place after a successful login and simply retrieve it everywhere you need it. You can - but that is a very inefficient approach to application design. Why? Think about it. You can try this approach but that does not change the need to remember a minimal set of login information.

So let's loop back to the prior comment about 2 code paths. Your "existing user" logic simply verifies that the username/password exist in a row in your table. I'll ignore the problems with storing passwords as plain text - you should not. And you should carefully consider what information is needed for a successful login based on the natural key of the table. Names are often not unique within a school, much less between schools. Again - as a learning experience this particular detail is not too important. As code to be implemented in a production system, it is very important.

When a user completes the new account logic, your app has all (or at least the vast majority of) the information associated with the user. Your login logic should do the same thing. Determine what information about the user your app needs, find a way to "remember" this information within your app, and then add the code to those paths to retrieve/save it. You may need to consider the opposite logic as well - provide a way to clear that information and return your app to the same state it was when first started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM