Home Ask Login Register

Developers Planet

Your answer is one click away!

Subpar Web Dev February 2016

Why am I getting 'Invalid attempt to read when no data is present' here?

My stored procedure is the simple one-liner

CREATE PROCEDURE CheckIfFinished    
    SELECT finished 
    FROM Partners 
    WHERE id = @pid   

and I'm calling it from my C# code like

using (SqlCommand cmd = new SqlCommand("CheckIfFinished", this._Conn))
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@pid", pid);


    using (SqlDataReader dataReader = cmd.ExecuteReader())
        finished = dataReader.GetByte(0) == 1 ? true : false;


The column finished in the Partners table is of type TINYINT NOT NULL DEFAULT 0

Stack trace of error is

[InvalidOperationException: Invalid attempt to read when no data is present.]
System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName) +6531242
System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) +81
System.Data.SqlClient.SqlDataReader.ReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) +25
System.Data.SqlClient.SqlDataReader.GetByte(Int32 i) +27
Survey.Models.SurveyDbModel.CheckIfFinished(Guid pid) +230

Where am I going wrong here?


Gusman February 2016

You forgot dataReader.Read().

Until you don't execute Read() on a data reader, the data is not available.

Post Status

Asked in February 2016
Viewed 2,514 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life