当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Do I need a using statement when setting a control's datasource to a sqldatareader

问题描述:

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 DataSource property 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{}.

using (SqlDataReader reader = getReader()) 
{ 
    ddlCustomer.DataSource = reader;
    ddlCustomer.DataBind(); 
} 
网友答案:

If I'm reading your question right, yes you would have to declare the SqlDataReader in the using statement:

using (SqlDataReader reader = getReader())
{
    ddlCustomer.DataSource = reader;  // get Reader returns a sqldataReader
    ddlCustomer.DataBind();
}

Binding the reader does not dispose it explicitly. If you want to do that, you can refactor this into a single method to bind a reader to a control:

public void BindControl(Control Ctl, SqlDataReader reader)
   {
        using (reader)
        {
          ddlCustomer.DataSource = reader;  // get Reader returns a sqldataReader
          ddlCustomer.DataBind();
        }
   }
网友答案:

BaseDataBoundControl makes no promise that it disposes of its data source, so callers must take responsibility themselves.

分享给朋友:
您可能感兴趣的文章:
随机阅读: