Getting a "There is already an open DataReader associated with this Command which must be closed first" error

778 views Asked by At

Even though I call close() on the reader, I still get the following error message:

There is already an open DataReader associated with this Command which must be closed first

It is only happening when there are 2 or more empty Document_No fields.

if (textBoxDocNum.Text == "")
{
    SqlConnection baglanti = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Visual\sw\sw\DMSDataBase.mdf;Integrated Security=True");
    baglanti.Open();
    SqlCommand emir = new SqlCommand("SELECT Document_No, Doc_IDN FROM Details WHERE Document_No = ''", baglanti);
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(emir);
    da.Fill(dt);

    foreach (DataRow dr in dt.Rows)
    {
        SqlCommand emir2 = new SqlCommand("SELECT Class, Type, Title, State, Date, Status FROM Document WHERE IDN = "+dr["Doc_IDN"].ToString(), baglanti);
        SqlDataReader dr2 = emir2.ExecuteReader(); //it explodes here
        dr2.Read();
        if (dr2[0].ToString()==comboBoxClass.Text && dr2[1].ToString() == comboBoxType.Text && dr2[2].ToString() == textBoxTitle.Text && dr2[3].ToString() == State && dr2[5].ToString() == Status)
        {
            labelDuplicate.Visible = true;
            return 0;
        }
        dr2.Close();
        baglanti.Close();
    }
}
1

There are 1 answers

0
JuanR On BEST ANSWER

I think your issue might be that when you return from inside the if statement, the reader will not be closed.

You should change your code to use using statements. That will close your reader even if you return. The same is true for the connection.

Your code has another flaw. I believe readers require an open connection. The first pass around the loop will close the connection if the condition is false, making the second pass fail.