SqlReader中的While循环问题 [英] While Loop Problem in SqlReader

查看:79
本文介绍了SqlReader中的While循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void gridfill()
    {
        reader = obj.SelCommand("Select type as TYPE,convert(varchar, fromdate, 103) as FROMDATE,convert(varchar, todate, 103) as TODATE,reason as REASON from tbl_leave where userid=(Select userid from tbl_login where username='" + lbluser.Text + "') and convert(varchar, todate, 103)>(select CONVERT(VARCHAR(10), getdate(), 103))");
        while (reader.Read())
            {
                DataTable DT = new DataTable();
                DT.Load(reader);
                leaveGrid.DataSource = DT;
                leaveGrid.DataBind();
            }
    }







public SqlDataReader SelCommand(string Command)
   {
       cmd = new SqlCommand(Command, con);
       dr = cmd.ExecuteReader();
       return dr;
   }



在这里,我试图从查询中读取值,如果读取,则将值加载到数据表中.但是第一次阅读后,它显示了一个错误
:关闭阅读器后尝试读取无效"



Here, I am trying to read value from a query and if read, then load the values to a datatable. But after reading first time, it is showing an error
:"Invalid attempt to READ when reader is closed"

Any help will be thankful

推荐答案

您使用错误的方式使用Reader对象填充数据表.您不需要像这样填充它,也可以在使用时使用它,但是可以提取特定的值并将其添加到数据表中,直到循环继续进行,循环结束时将数据表分配给网格.

改为尝试以下方式:
You are using wrong way to fill datatable using Reader object. You don''t need while to fill it like this OR you can use while but then extract specific values and add them to datatable till loop goes on, ones loop ends assign datatable to grid.

Try this way instead:
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
    {
      myConnection.Open();
      using (SqlDataReader myReader = myCommand.ExecuteReader())
      {
        DataTable myTable = new DataTable();
        myTable.Load(myReader);
        myConnection.Close();
        return myTable;
      }
    }


这篇关于SqlReader中的While循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆