Reading from a SQL database

Self explanatory snippet


SqlConnection db = new SqlConnection(Properties.Settings.Default.ConnectionString);

            
try
{
   db.Open();
   SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT FirstName, LastName  FROM Contacts", db);

   DataTable dataTable = new DataTable();
   dataAdapter.Fill(dataTable);

   foreach(DataRow row in dataTable.Rows)
   {
      string firstName = row["FirstName"];
      string lastName  = row["LastName"];
   }
 
   db.Close(); 
   db.Dispose(); 
   db = null;0
}
catch (Exception e)
{
   System.Windows.Forms.MessageBox.Show(e.Message, "DB error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);      
}
Lastest update in February 2012, inital post in February 2012

Write a comment

I appreciate comments, suggestions, compliments etc. Unfortunately I have no time to reply to them. Useful input will be used for sure!