Wednesday, 26 November 2014

How to get data from db and store in array list and diplay it using foreach loop

  1. SqlConnection con = new SqlConnection("Data Source=XXXXX;Initial Catalog=XXXXX;Persist Security Info=True;User ID=XXXXX;Password=XXXXX");
  2. SqlCommand cmd = new SqlCommand();
  3. cmd.CommandText = ("Select * from Employee");
  4. cmd.Connection = con;
  5. try
  6. {
  7. con.Open();
  8. SqlDataReader dr = cmd.ExecuteReader();
  9. ArrayList Al = new ArrayList();
  10. if (dr.HasRows)
  11. {
  12. while (dr.Read())
  13. {
  14. Al.Add(dr.GetInt32(0) + " , " + dr.GetString(1) + "," + dr.GetDateTime(2) + "," + dr.GetString(3));
  15. }
  16. }
  17. dataGridView1.DataSource = Al;
  18. }
  19. finally
  20. {
  21. con.Close();
  22. }

0 comments:

Post a Comment