Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid attempt to call MetaData when reader is closed?

I'm running an if else statement off of a datareader to query table data and activate/de-activate some controls on a page. I implemented a using statement to automatically close the connection and the reader when I close the block, but I still get the reader is closed error on each of my if else statements. What's missing? Code below:

string comnt = "SELECT StatusId FROM Submission WHERE SubmissionId =" + x;


    using (SqlConnection editConn = new SqlConnection(connectionString))
    {
        editConn.Open();

        using (SqlCommand statCmd = new SqlCommand(comnt, editConn))
        {
            SqlDataReader dr = statCmd.ExecuteReader();
            dr.Read();
            if (dr.GetInt32(0) > 0)
            {
                PanelComment.Visible = true;
                PanelQuote.Visible = false;
                LnbFid.Visible = false;
                LnbCrim.Visible = false;
                LnbEo.Visible = false;
                LnbEpl.Visible = false;
                LnbNot.Visible = false;
                LnbPriv.Visible = false;
                LnbPub.Visible = false;

            }
            else
            {
                PanelComment.Visible = false;
            }

        } 
like image 265
Ace Troubleshooter Avatar asked May 30 '11 17:05

Ace Troubleshooter


3 Answers

Your query is not getting any results back. Get used to the following construct if you are not sure if your query will return any data:

while (dr.Read()) //will return true while there is data to be read.
{
    ...
}
like image 35
InBetween Avatar answered Sep 20 '22 15:09

InBetween


I faced this problem due to mismatch of reader name. i.e.

SqlCommand sqlmd = new SqlCommand();
SqlDataReader sqldr = sqlmd.ExecuteReader();
while (sqldr.Read())
{

    idd = (int)rdr["Id"];
}

later I replaced the code

 idd = (int)sqldr["Id"];

and the error was solved.

like image 22
user1780336 Avatar answered Sep 18 '22 15:09

user1780336


Try this way:

if (dr.HasRows)
{
     while (dr.Read())
     {
         if (dr.GetInt32(0) > 0)
         {
             ...
         }
     }
}

For more info, check this page:

Retrieving Data Using a DataReader

like image 179
Leniel Maccaferri Avatar answered Sep 20 '22 15:09

Leniel Maccaferri