Home > OS >  How to get other values from SQLDataAdapter command
How to get other values from SQLDataAdapter command

Time:09-15

so i have this code which is used by a login winforms app.

            String querry = "SELECT * FROM Accs WHERE email = '"   richTextBox1.Text   "' AND password = '"   richTextBox2.Text   "'";
            SqlDataAdapter sda = new SqlDataAdapter(querry, 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 account table screenshot

CodePudding user response:

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"];
            }

CodePudding user response:

String querry = "SELECT TOP 1 * FROM Accs WHERE email = '"   richTextBox1.Text   "' AND password = '"   richTextBox2.Text   "'";
        SqlDataAdapter sda = new SqlDataAdapter(querry, 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 querry = "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 querry = "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

  • Related