已经有一个与此命令关联的开放DataReader,必须先关闭

时间:2017-12-16 12:24:32

标签: c#

  

“此命令已经有一个打开的DataReader关联   必须先关闭。“

当我'搜索'“命名”来自搜索按钮的数据时。我收到了这个错误。

这是代码:

private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand selectCommand = new SqlCommand("Select * from New_table where Name = @name", conn);
                selectCommand.Parameters.Add(new SqlParameter("name", textname.Text.ToString()));
                SqlDataReader reader = selectCommand.ExecuteReader();
                bool rowFound = reader.HasRows;
                if (rowFound)
                {
                    while (reader.Read())
                    {
                        textname.Text = reader.GetString(0).ToString();
                        txtaddress.Text = reader.GetString(1).ToString();
                        txtcontact_no.Text = reader.GetString(2).ToString();

                        SqlDataAdapter data = new SqlDataAdapter("Select * from New_table", conn);
                        DataTable dt = new DataTable();
                        data.Fill(dt);
                        dataGridView1.DataSource = dt;
                        MessageBox.Show("Search Found", "Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("User Not Found", "Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

1 个答案:

答案 0 :(得分:0)

您正尝试在单个连接中执行两个查询或批处理因此问题。有两种方法可以解决。

1.从全局某处读取sql reader的读取数据,再次使用新连接调用sql adapter并输入该数据。

2.或在您的连接字符串中使用多个活动结果集属性,以便您可以在单个连接上执行多个批次

string connectionString = "Data Source=MSSQL1;" +   
    "Initial Catalog=AdventureWorks;Integrated Security=SSPI;" +  
    "MultipleActiveResultSets=True";

注意:顺便说一句,你应该避免这种情况。