The code performs as needed when done like this.
SqlDataReader sqlRead = selectCommand.ExecuteReader(CommandBehavior.SingleRow);
if (sqlRead.Read())
{
string text = sqlRead["USERNAME"].ToString();
MessageBox.Show(text);
connection.Close();
}
Whenever written without the if and just the variable declaration like this
string text = sqlRead["USERNAME"].ToString();
MessageBox.Show(text);
connection.Close();
I get this error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: Invalid attempt to read when no data is present.
Why can't I simply assign the value to the variable? Is it because nothing was actually read into the reader?
sqlRead.Read()fetches the next record from cursor and returntrueon success, if you don't have any record fetched (data present) you can't read it