Articles → CSHARP → Using Statement In C#

Using Statement In C#






Purpose




SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader = null;

SqlCommand cmd = new SqlCommand(commandString, connection);
connection.Open();
reader = cmd.ExecuteReader();

while (reader.Read()) {
  listBox1.Items.Add(reader[0].ToString() + ", " + reader[1].ToString());
}

reader.Close();
connection.Close();






reader.Close();
connection.Close();




  1. Use the Try-Catch-Finally block and close Datareader and connection in the Finally block
  2. Use the "using" statement to ensure that the Datareader and connection object will be closed before exiting the loop

Using Statement In Action




using(SqlConnection connection = new SqlConnection(connectionString)) {
  SqlCommand cmd = new SqlCommand(commandString, connection);
  connection.Open();

  using(SqlDataReader reader = cmd.ExecuteReader()) {
    while (reader.Read()) {
      listBox1.Items.Add(reader[0].ToString() + ", " + reader[1].ToString());
    }
  }
}



Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, November 30, 2010

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250