Saturday, March 24, 2012

Strange error with SqlDataReader

Hi,
I am using a datareader to fill a datagrid in a usercontrol. I use this method a lot in my application but for an unknown reason, I get this error message in only one web form: "Invalid attempt to FieldCount when reader is closed". What is strange is that the reader is actually open when the error is occuring. The only thing I see that could cause an error is that the user control is created from another usercontrol just after closing another SqlDataReader:

Calling user control


SqlDataReader rdr = cmd.ExecuteReader();
childUC = (DynamicUC)LoadControl( rdr["ASCXDynPage"].ToString() + ".ascx" );
childUC .Language = rdr["NoLanguage"].ToString();
rdr.Close();
childUC.DataBind();

Called user control (DataBind method)

... Creating SQLCommand here ...
SqlDataReader rdr = cmd.ExecuteReader();
gridNews.DataSource = rdr;
gridNews.DataBind();
gridNews.Visible = true;
rdr.Close();

After some tests, the error seam to happen when I set the DataSource of the DataGrid with the DataReader. Also, the error is set at the line where I call the DataBind method of the UserControl childUC. Anyone ever saw that kind of behavior?Maybe your query hasn´t data.
I suggest you use a dataset as datasource of the datagrid.
The query has data.
I tried the dataset, it works. But I really want to know what is wrong with that piece of code... I really don't understand what is going on...

0 comments:

Post a Comment