Articles → .NET → Using Statement In C#

Using Statement In C#





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 Try-Catch-Finally block and close datareader and connection in Finally block.
  2. Using statement to ensure that datareader and connection object will be closed before exiting the loop.
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