Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Analysis- Do not dispose objects multiple times

When i analyzed my code from Visual Studio 2013 some warnings appear that "Do not dispose objects multiple times " it also stated that object conn disposed multiple times in object but as i know if i did not use this object multiple times in object than i cant achieve my goals. so kindly tell me how i can remove this warning ?

here is my code :

private void GetData()
        {
            DataTable dt = new DataTable();
            _connString = ConfigurationManager.AppSettings["connString"];
            using (SqlConnection conn = new SqlConnection(_connString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select * from ref_CourseRegistration_Users", conn);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                conn.Close();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grdUsers.DataSource = ds;
                    grdUsers.DataBind();
                }
            }
        }

here is screenshot of my analysis : enter image description here

like image 748
Wasay Avatar asked Jun 27 '26 19:06

Wasay


1 Answers

Here if you are using the using statement

using (SqlConnection conn = new SqlConnection(_connString))

no need to close the connection again so conn.Close(); is not required.

It'll automatically dispose the object.

like image 101
tarzanbappa Avatar answered Jun 30 '26 07:06

tarzanbappa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!