I was trying to to use parameterized query with data reader when I get this error message “Invalid attempt to read when no data is present.”
But data is there is the reader!

Following is the line of code which performs this task
using (ConnectionManager connectionManager = new ConnectionManager())
{
string query = @"SELECT * FROM LoginTab WHERE username=@username " +
"AND password=@password";
List<SqlParameter> sqlParameterCollection = new List<SqlParameter>();
sqlParameterCollection.Add(new SqlParameter("@username", SqlDbType.NVarChar) { Value = userName });
sqlParameterCollection.Add(new SqlParameter("@password", SqlDbType.NVarChar) { Value = password });
SqlDataReader sqlDataReader = connectionManager.ExecuteReader(query, CommandType.Text, sqlParameterCollection);
String roles = sqlDataReader[0].ToString();
return roles;
}
ExecuteReader function is defined in another class.
public SqlDataReader ExecuteReader(String strcmd, CommandType type, List<SqlParameter> Parametercollections)
{
connnection = new SqlConnection(Connnectionstring);
command = new SqlCommand(strcmd, connnection);
command.CommandType = type;
foreach (SqlParameter paras in Parametercollections)
{
command.Parameters.Add(paras);
}
try
{
connnection.Open();
reader = command.ExecuteReader();
}
catch (SqlException E)
{
}
finally
{
}
return reader;
}
What could be wrong here?
When you call
SqlCommand.ExecuteReader(), theSqlDataReaderthat it gives you is initially positioned before the first record. You must callSqlDataReader.Read()to move to the first record before attempting to access any data.SqlDataReader.Read()returnstrueif it was able to move to the first record; it returnsfalseif there are no records.