I got this error "Invalid attempt to call Read when reader is closed" when I close dataReader inside While

Osama Abdelkader 1 Reputation point
2021-11-08T02:14:36.127+00:00
while (dr.Read())
                {
                    conn.Open();
                    string Qry = "SELECT COUNT(*) FROM tbl')";
                    SqlCommand com = new SqlCommand(Qry, conn);
                    int Cond = Convert.ToInt32(com.ExecuteScalar().ToString());
                    conn.Close();
                    if (Cond == 0)
                    {
                        //Do Some Actions
                    }
                    else
                    {
                        dr.Close();
                        myCon.Close();

                    }
                }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,197 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 24,276 Reputation points Microsoft Vendor
    2021-11-08T06:57:32.53+00:00

    @Osama Abdelkader , If you want to get the count of the rows in the table, there is no need to use the SqlDatareader.

    Here is a code example you could refer to.

    Code:

            string connstr = "connstr";  
            SqlConnection connection = new SqlConnection(connstr);  
            connection.Open();  
            string comamnd = "select COUNT(*) from Student";  
            SqlCommand com = new SqlCommand(comamnd, connection);  
            int Cond = Convert.ToInt32(com.ExecuteScalar().ToString());  
            Console.WriteLine(Cond);  
            connection.Close();  
    

    Hope the code example could help you. If I have some misunderstanding, Pleas feel free to let me know.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Viorel 111.7K Reputation points
    2021-11-08T09:13:29.527+00:00

    Probably you should add a break after myCon.Close.

    Or maybe you can use if instead of while.

    0 comments No comments