Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
I get this Error when call the page again:
There is already an open DataReader associated with this Command which must be closed first

C#
public static SqlDataReader FillGridView()
        {
            SqlCommand SqlCmd = new SqlCommand("SELECT * FROM MYTABLE");
            SqlCmd.Connection = conn;
            SqlCmd.CommandType = CommandType.Text;
            SqlDataReader SqlRd = SqlCmd.ExecuteReader();            
            return SqlRd;           
        }
Posted
Updated 10-Jun-11 5:21am
v2

Use CommandBehaviour as a parameter for the ExecuteReader method. Also close the reader once the usage is over by calling the Close() method.

SqlDataReader SqlRd = SqlCmd.ExecuteReader(CommandBehaviour.CloseConnection);


Click here[^] for more details.
 
Share this answer
 
v2
Comments
TheCodeVB 10-Jun-11 14:08pm    
With this parameter Works.
This is not the way to use SQLDataReader:
SqlDataReader SqlRd = SqlCmd.ExecuteReader();
return SqlRd;

SQLDatareader is connected mode thing and thus you cannot just return it's instance without closing it.

Look here and read on how to use it:
Retrieving Data Using a DataReader (ADO.NET)[^]
SqlDataReader Class[^]
 
Share this answer
 
This may help to you..
Better to use DataTable than the DataReader
public static DataTable FillGridView()
{
    DataTable dt = new DataTable();
    SqlCommand SqlCmd = new SqlCommand("SELECT * FROM MYTABLE",conn);
    SqlCmd.CommandType = CommandType.Text; // no need of this line it is by detault.
    try
    {
        conn.Open();
        dt.Load(SqlCmd.ExecuteReader());
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : "+ex.Message);
    }
    return dt;
}
 
Share this answer
 

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