lundi 2 novembre 2015

Yet another "Invalid attempt to read when no data is present." error

I'm trying to pull one field from a view in my database. I determined there is data for this one instance, I correctly set up the SQLDataReader (I believe), the debugger verifies that I have rows in the DataReader, yet when I try to read I get an error.

Here's the code:

    public string[] getReasons(string Accession) {
        string[] reasonList = new string[0];
        SqlParameter accNumber = new SqlParameter();
        accNumber.SqlDbType = System.Data.SqlDbType.VarChar;
        accNumber.ParameterName = "@Accession";
        accNumber.Value = Accession;
        string selectText = "select reason from pendingList where accession = @Accession";
        SqlCommand selectStmt = new SqlCommand(selectText,toPending);
        selectStmt.Parameters.Add(accNumber);

        if (selectStmt.Connection.State == System.Data.ConnectionState.Closed) {
            selectStmt.Connection.Open();
        }
        SqlDataReader pendList = selectStmt.ExecuteReader();

        while (pendList.Read()) {
            reasonList[reasonList.Length] = pendList["reason"].toString();
        }

        pendList.Close();

        return reasonList;
    }

I call getReasons('RAM4658980'). I've verified that the following SQL query

select reason 
from pendingList 
where accession = 'RAM4658980'

returns exactly one row. The pendList variable looks like this:

pendList variable contents

I'm not sure why I get "Enumeration yielded no results"; and at the reasonList[reasonList.Length] = pendList["reason"].toString(); step, I naturally get the "Invalid attempt to read ..." error. What am I missing?

Aucun commentaire:

Enregistrer un commentaire