Getting an Invalid attempt to read when Reader is closed
exception in my duplicateNameCheck
method, when attempting to read from the DataReader. I'm not sure why. Any help is greatly appreciated!
public static MySqlConnection GetSqlConnection() {
MySqlConnection connection = new MySqlConnection(connectionString);
return connection;
}
public static MySqlDataReader ExecuteReader(string sqlQuery, MySqlConnection connection) {
using (MySqlCommand command = new MySqlCommand(sqlQuery, connection)) {
try {
connection.Open();
MySqlDataReader sqlReader = command.ExecuteReader();
return sqlReader;
} catch (Exception ex) {
MessageBox.Show(ex.Message);
return null;
}
}
}
public static bool duplicateNameCheck(string inName) {
String sqlQuery = "SELECT * FROM Account";
using (MySqlDataReader sqlReader = SQLHelper.ExecuteReader(sqlQuery, SQLHelper.GetSqlConnection())) {
while (sqlReader.Read())
{
if (inName.Equals(sqlReader[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
}
return false;
}
You're disposing the SqlCommand before attempting to use the SqlReader it produced. They'll both need to stay open until you're done with the reader.