When working with databound controls in asp.net, is there a good pattern for making sure everything is disposed properly?
Here’s what I have so far:
using (var conn = New SqlConnection("connectionString"))
using (var cmd = conn.CreateCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "myProc";
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
gridview1.DataSource = rdr;
gridview1.DataBind();
}
}
Do I need to close the datareader / command / connection? Or does the using statement take care of this automatically? Or maybe there is a better pattern when using databound controls?
Your code seems right. The only possible changes are:
CommandBehavior.CloseConnectionto the ExecuteReader (no really necessary with the flow ofusingstatements)But they are really little things.