-1

I have this code which is used by a login in a Winforms app.

String query = "SELECT * FROM Accs WHERE email = '" + richTextBox1.Text + "' AND password = '" + richTextBox2.Text + "'";

SqlDataAdapter sda = new SqlDataAdapter(query, conn);

DataTable dtable = new DataTable();
sda.Fill(dtable);

if (dtable.Rows.Count > 0)
{
    // the login operation is successful
    email = richTextBox1.Text;
    pass  = richTextBox2.Text;
}

What I want to do is to take the "username" value from the same row.

How can I do that?

This is my accounts table:

SQL Server account table screenshot

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Correct me if I'm wrong, but it seems that you are looking for

            if(dtable.Rows.Count > 0)
            {
                //the login operation is successful
                email = richTextBox1.Text;
                pass  = richTextBox2.Text;
                username = dtable.Rows[0]["username"];
            }
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0
String query = "SELECT TOP 1 * FROM Accs WHERE email = '" + richTextBox1.Text + "' AND password = '" + richTextBox2.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, conn);

DataTable dtable = new DataTable();
sda.Fill(dtable);

if (dtable.Rows.Count > 0)
{
    // the login operation is successful
    email = richTextBox1.Text;
    pass  = richTextBox2.Text;
}

You can select only 1 row by adding TOP 1 in the start of the query to get only 1 result and yes if you want the username you can get it from

if (dtable.Rows.Count > 0)
{
   // the login operation is successful
   email = rickTextBox1.Text;
   pass = rickTextBox1.Text;
   username = dtable.Rows[0]["username"];
}

Since the image you provided shows that the username column in your database is the first one so you can do it like this as well inside your for loop

username = dtable.Rows[0][0];

or you can change your query to like this to get only the username

String query = "SELECT TOP 1 username FROM Accs WHERE email = '" + richTextBox1.Text + "' AND password = '" + richTextBox2.Text + "'";

Instead of getting all the columns you can query for the require column by replacing * in the select command with the column or columns that you are needed for example if you want username and password you can pass this query as well

String query = "SELECT TOP 1 username,email FROM Accs WHERE email = '" + richTextBox1.Text + "' AND password = '" + richTextBox2.Text + "'";

in the last query you will get 2 columns if the passing arguments are correct and database has record against that entry

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459