NewPassionnate
NewPassionnate

Reputation: 179

store value from sql statement in variable

My user logs in with username and password, I check in the database if he exists.
I would like after the connection, to get the UserID from the connected user and put it in a variable that I will be able to user later on in my program.


My table user and my two functions. i didn't add all the code as I don't think it is necessary.


+-----------------------------------------+
|    User                                 |
+------------+------------+---------------+
| UserID     | Username   | password      |
| 1          | abc        |  def          |
| 2          | ghi        |   jkl         |
+------------+------------+---------------+
 public int Login(string Username, string Password)
    {
        try
        {
            clsDataSource.mycon = new OleDbConnection(@"Provider=...");
            OleDbCommand cmd = new OleDbCommand("Select * from Users where email=@email and pwd=@pwd", clsDataSource.mycon);
            cmd.Parameters.AddWithValue("@email",Username);
            cmd.Parameters.AddWithValue("@pwd",Password);
            clsDataSource.mycon.Open();
             dr = cmd.ExecuteReader();              
            DataTable dt = new DataTable();
            dt.Load(dr);                    

            clsDataSource.mycon.Close();

           //code to login

            return 0;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


 private void button1_Click(object sender, EventArgs e)
    {            
        //code to check the login

    }

Upvotes: 2

Views: 72

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

Change the return 0 in Login to

return dt.Row[0]["ID"];

Then in button1_Click

userId = Login(...)

Upvotes: 0

Doniyor Niazov
Doniyor Niazov

Reputation: 1431

Check this:

var ID = (int)cmd.ExecuteScalar();

this should help!

Upvotes: 1

Related Questions