Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
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();
            }
    }



C#
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
Posted
Updated 2-Feb-11 17:27pm
v3

1 solution

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:
C#
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;
      }
    }
 
Share this answer
 
Comments
Nithin Sundar 3-Feb-11 0:05am    
Good answer! 5!
Espen Harlinn 6-Feb-11 11:48am    
Nice and simple, a 5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900