I am attempting to create a login form using a username and password from a database table named "Table". I have watched several videos and looked at several other pages and can not seem to get the query to run correctly. My second try/catch block shows the message box "could not run query". Will someone look at my code to see what is wrong, please and thank you.
SqlConnection con = new SqlConnection();
string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Donovan\Documents\Work\Time Clock program\Time Clock program1.2\Time Clock program\Database1.mdf;Integrated Security=True;Connect Timeout=30;";
string query = "SELECT Count(*) FROM [Table] WHERE Username='" + usernameTextBox.Text +
"' AND Password = '" + this.passwordTextBox.Text + "'";
try
{
con = new SqlConnection(connectionString);
}
catch(Exception ex)
{
MessageBox.Show("Could not connect to Database");
MessageBox.Show(ex.Message);
}
try
{
if (!(usernameTextBox.Text == string.Empty))
{
if (!(passwordTextBox.Text == string.Empty))
{
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dbr;
con.Open();
dbr = cmd.ExecuteReader();
int count = 0;
while (dbr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("username and password is correct");
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password", "login page");
}
else
{
MessageBox.Show(" username and password incorrect", "login page");
}
}
else
{
MessageBox.Show(" password empty", "login page");
}
}
else
{
MessageBox.Show(" username empty", "login page");
}
// con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}