I have a class which connects to the db(sql server). I have a login class which authenticates the user away from the frmLogin form. Each time i click login, i get an error Executereader requires an open connection. I tried reversing the order of some variables but to no success.
here's the code for the connection class
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Albergo
{
class Connect
{
public String connectionString = null;
SqlConnection sqlCon;
public Connect()
{
connectionString = "Data Source=SALITY-EXE\\PHILSOFTSQL;Initial Catalog=albergo;Persist Security Info=True;User ID=sa;Password=t3rminat0rz!";
sqlCon = new SqlConnection(connectionString);
}
public Boolean OpenCon()
{
try
{
sqlCon.Open();
return true;
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show("Can not open connection ! " + ex.Message);
return false;
}
}
public Boolean CloseCon()
{
try
{
sqlCon.Close();
return true;
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show("Connection is already closed" + ex.Message);
return false;
}
}
}
}
heres the code for the Login
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Albergo.Classes
{
class Login
{
String username;
String password;
String sql;
Connect connect;
SqlConnection con;
SqlCommand cmd;
SqlDataReader datareader;
public Login(String username, String password)
{
this.username = username;
this.password = password;
Connect connect = new Connect();
con = new SqlConnection(connect.connectionString);
sql = "SELECT * FROM users WHERE username = '" + username + "' and password = '" + password;
}
public int authenticate()
{
connect = new Connect();
try
{
connect.OpenCon();
cmd = new SqlCommand(sql, con);
datareader = cmd.ExecuteReader();
datareader.Read();
if (datareader.HasRows)
{
datareader.Close();
connect.CloseCon();
return 1;
}
else
{
datareader.Close();
connect.CloseCon();
return 0;
}
}
catch (Exception ex)
{
MessageBox.Show("There was a problem while trying to Connect: " + ex.Message);
return 0;
}
}
}
}
Please help me identify the error...