zahra al lawati
zahra al lawati

Reputation: 1

how to use if statement to retrieve a row of data from sql server using c#

Good day

I am working on login page where the user will be able to login if a value is shown in the database table and if it is not shown it will displays for him a change password page.

What I want is, how can I write an if statement to retrieve username and password if that value is exiting or not ?

what I have tried is the following

con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("select count (*) from log_sup where ENTITY_DIVISION_CODE = '" + textBox1.Text + "'and DX_NUMBER = '" + textBox2.Text + "'" );
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();

if (dt.Rows[0][0].ToString() == "1" )
{
     Form2 f2 = new Form2();
     f2.Show();
     this.Hide();
}

else
{
     MessageBox.Show("THE USERNAME OR PASSWORD IS INVALID. THIS IS YOUR    " , MessageBoxButtons.OK);
     Form3 F3 = new Form3();
     F3.Show();
     this.Hide();
}
con.Close();

Upvotes: 0

Views: 252

Answers (1)

Gaurang Dave
Gaurang Dave

Reputation: 4046

COUNT() is a scalar function so use cmd.ExecuteScalar(); to get result as an Object. No need to take DataTable and do other complex things.

Following is simple solution. Kindly modify accordingly as its just a help how to use ExecuteScalar.

int result = Convert.ToInt32(cmd.ExecuteScalar());
if(result > 0)
{
    //SUCCESS
}
else
{
    //FAIL
}

Upvotes: 1

Related Questions