I am working C# Form and SQL Server. I had a problem when login.
"System.InvalidOperationException: 'Connection was not closed'.
I can't solve this problem. I think I add much "con.Open()
". But I try much way but I take still this error. Guess, I deleted one more open and close, is it true?
private void buttonLogin_Click(object sender, EventArgs e)
{
con.Open();
if (String.IsNullOrEmpty(textBoxUserName.Text))
{
MessageBox.Show("Username can't be empty");
textBoxUserName.Focus();
con.Close();
}
if (String.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Password can't be empty");
textBoxPassword.Focus();
con.Close();
}
else
{
con.Open();
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM Users WHERE username ='" + textBoxUserName.Text.Trim() + "' and password= '" + textBoxPassword.Text.Trim() + "'");
SqlDataReader myReader;
myReader = SelectCommand.ExecuteReader();
int count = 0;
string userRole = string.Empty;
while (myReader.Read())
{
count = count + 1;
userRole = myReader["userrank"].ToString();
}
if (count == 1)
{
if (userRole =="admin" )
{
Form1 form = new Form1();
this.Hide();
form.Show();
con.Close();
}
else
{
UI ui = new UI();
this.Hide();
ui.Show();
con.Close();
}
myReader.Close();
}
else
{
MessageBox.Show("Check your username or password");
con.Close();
}
}
}