本文介绍了sqldatareader错误“关闭阅读器时,无效的调用Read的尝试."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
当我从sqldatareader读取数据时,出现错误关闭阅读器时,无效的尝试调用Read的尝试."
我的代码是

Hello there,
when I am reading data from sqldatareader I am getting error "Invalid attempt to call Read when reader is closed."
My code is

string cid = "a";

            string s = "select Student_Id from tbstudent_batchmaster where Batch_Identity='" + batchid + "'";

            ClsConnection.Conn.Close();
            ClsConnection.Conn.Open();

            SqlCommand cmd = new SqlCommand(s, ClsConnection.Conn);

            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {

                cid = sdr.GetValue(0).ToString();
                
                Int32.TryParse(cid, out  actval);
               // fillstudentdata();

                ClsConnection.Conn.Close();
                ClsConnection.Conn.Open();

                dtstudent.ColumnHeadersVisible = true;
                dtstudent.RowHeadersVisible = false;
                dtstudent.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                string selectCommand1 = "select  FName+' '+LName as Name from ADD_Master where ADD_No='" + actval + "'";
                SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter(selectCommand1, ClsConnection.Conn);
                SqlCommand cmd1 = new SqlCommand();

                cmd1.CommandText = selectCommand1;
                DataSet ds1 = new DataSet();
                sqlDataAdapter1.Fill(ds1);
                ClsConnection.Conn.Close();
                dtstudent.DataSource = ds1.Tables[0];
                DataGridViewCheckBoxColumn cb = new DataGridViewCheckBoxColumn();
                cb.HeaderText = "test";
                cb.Name = "test";
                cb.Visible = true;
                cb.Width = 40;
                dtstudent.Columns.Add(cb);
                dtstudent.Columns[0].Visible = false;
                dtstudent.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dtstudent.Refresh();
                

            }
           

            ClsConnection.Conn.Close();
        }


有谁可以帮忙????请.


can any one help ???? please.

推荐答案



SqlConnection connection = new SqlConnection(connectionString);
using(connection) // will make certain that the connection is properly disposed
{
 connection.Open();
 SqlCommand command = connection.CreateCommand();
 using(command) // will make certain that the command is properly disposed
 {
  command.CommandText = sqlStatement;
  SqlDataReader dataReader = command.ExecuteReader();
  using(dataReader) // will make certain that the reader is properly disposed
  {
   while(dataReader.Read())
   {
     // process records. don''t close and open the connection
   }
  }
 }
}



最好的问候
Espen Harlinn



Best regards
Espen Harlinn


这篇关于sqldatareader错误“关闭阅读器时,无效的调用Read的尝试."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 06:15