Before performing any operation on the DataTable you need to add the following namespace into your application.

Using System.Data

Introduction

DataTable is a Table which has rows and columns.

  1. using System;
  2. using System.Data;
  3. namespace OperationOnDataTable
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. // Initializes a new instance of the System.Data.DataTable class with the specified table name.
  10. DataTable tempTable = new DataTable();
  11. // Add columns in DataTable
  12. tempTable.Columns.Add("ID");
  13. tempTable.Columns.Add("NAME");
  14. // Add New Row in dataTable
  15. DataRow newrow = tempTable.NewRow();
  16. newrow[0] = 0;
  17. newrow[1] = "Avinash";
  18. tempTable.Rows.Add(newrow);
  19. // Add Another New Row in dataTable
  20. newrow = tempTable.NewRow();
  21. newrow[0] = 1;
  22. newrow[1] = "Kavita";
  23. tempTable.Rows.Add(newrow);
  24. //Now table is ready
  25. Console.WriteLine("Origenal table");
  26. for (int i = 0; i < tempTable.Rows.Count; i++)
  27. {
  28. Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
  29. }
  30. // if you want edit data form TataTable
  31. Console.WriteLine("\nModified table");
  32. for (int i = 0; i < tempTable.Rows.Count; i++)
  33. {
  34. if (tempTable.Rows[i][1].ToString() == "Kavita")
  35. {
  36. tempTable.Rows[i][1] = "gare";
  37. }
  38. Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
  39. }
  40. // if you want delete row form TataTable
  41. Console.WriteLine("\nAfter deleting row from table");
  42. for (int i = 0; i < tempTable.Rows.Count; i++)
  43. {
  44. if (tempTable.Rows[i][1].ToString() == "gare")
  45. {
  46. tempTable.Rows[i].Delete();
  47. }
  48. }
  49. for (int i = 0; i < tempTable.Rows.Count; i++)
  50. {
  51. Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
  52. }
  53. Console.ReadLine();
  54. }
  55. }
  56. }

OUTPUT

Original table

0--->Avinash
1--->Kavita

Modified table
0--->Avinash
1--->gare

After deleting row from table

0--->Avinash