Simple DataGrid Example In C#

This snippet shows how to add rows to a DataGrid control using the DataRow class.


  1. DataTable products = new DataTable("Product List");
  2. DataColumn name = new DataColumn("Product Name");
  3. DataColumn price = new DataColumn("Product Price");
  4. products.Columns.Add(name);
  5. products.Columns.Add(price);
  6. DataRow product1 = products.NewRow();
  7. product1["Product Name"] = "180 Hard Drive";
  8. product1["Product Price"] = 39.00;
  9. DataRow product2 = products.NewRow();
  10. product2["Product Name"] = "MP3 Player";
  11. product2["Product Price"] = 29.99;
  12. DataRow product3 = products.NewRow();
  13. product3["Product Name"] = "128 Graphics Card";
  14. product3["Product Price"] = 49.99;
  15. products.Rows.Add(product1);
  16. products.Rows.Add(product2);
  17. products.Rows.Add(product3);
  18. DataGrid grid = new DataGrid();
  19. grid.Dock = DockStyle.Fill;
  20. grid.DataSource = products;
  21. this.Controls.Add(grid);

No comments:

Post a Comment