出现 "There is already an open DataReader associated with this Command which must be closed first" 错误

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

即使我在 reader 上调用 close(),我仍然收到以下错误消息:

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

只有当有 2 个或更多空 Document_No 字段时才会发生。

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();
    }
}

我认为您的问题可能是当您从 if 语句中 return 时,reader 不会关闭。

您应该更改代码以使用 using 语句。即使您 return,这也会关闭您的 reader。连接也是如此。

您的代码还有另一个缺陷。我相信 readers 需要一个开放的连接。如果条件为假,循环的第一遍将关闭连接,使第二遍失败。