The best way is like this for a DataReader:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT description FROM myTable WHERE Id = @ID", con))
{
cmd.Parameters.AddWithValue("@ID", userId);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = (int) reader["Id"];
string desc = (string) reader["description"];
Console.WriteLine("ID: {0}\n {1}", id, desc);
}
}
}
}
And this for a DataAdapter:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
{
da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
DataTable dt = new DataTable();
da.Fill(dt);
myDataGridView.DataSource = dt;
}
}
The
using
blocks ensure that the objects are closed and disposed automatically when you are finished with them.