I have this below code to retrieve data from db and when I run the Code Analysis from Visual Studio, it suggests me to call dispose method on SqlConnection
, DataTable
and SqlDataAdapter
objects.
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
SqlCommand cmd = sqlconn.CreateCommand();
cmd.CommandText = "SELECT * FROM tbl_serial WHERE serial = @serial";
cmd.Parameters.AddWithValue("@serial", txtQuery.Text);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
sqlconn.Open();
da.SelectCommand = cmd;
da.Fill(dt);
}
catch (SqlException ex)
{
lblStatus.Text = ex.Message;
}
finally
{
sqlconn.Close();
}
if (dt.Rows.Count > 0)
{
lblStatus.Text = "FOUND!";
}
else
{
lblStatus.Text = "NOT FOUND!";
}
And this is my first time doing this, I called dispose method on sqlconn
just like this -
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
But then, Visual Studio warns me like this -
CA2202 : Microsoft.Usage : Object 'sqlconn' can be disposed more than once in method 'test_search.Unnamed1_Click(object, EventArgs)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 41
So I would like to know when should I correctly call dispose methods.