I know it is recommended to use a using statement with a sqldatareader, but I was wondering if it is necessary when you are setting the datasource of a control to a datasource directly.
in some places in my code I do this…..
using (SqlDataReader reader = getReader())
{
while (reader.Read())
{
// do stuff with data
}
}
when binding to a control I do this…..
ddlCustomer.DataSource = getReader(); // get Reader returns a sqldataReader
ddlCustomer.DataBind();
In the second case, do I need to use a using statement. Do i have to first declare an SqlDataReader in a using statement, then set the DataSource to that object. Seems like more clutter in the code, so i was hoping binding to the SqlDataReader disploses of the SqlDataReader.
Thanks
At some point, the Dispose() method on the DataReader needs to be called. The finalizer will do it for you sometime in the future, but that’s probably to late.
So, the question becomes, “If I don’t, who will?”
There’s a chance that the DataBind() method will recognize that the object assigned to the
DataSourceproperty is an IDisposable, and call Dispose when it’s finished Databinding, but I wouldn’t count on it.So, yes, I’d go with the
using{}.