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.
- using System;
- using System.Data;
- namespace OperationOnDataTable
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- DataTable tempTable = new DataTable();
-
- tempTable.Columns.Add("ID");
- tempTable.Columns.Add("NAME");
-
- DataRow newrow = tempTable.NewRow();
- newrow[0] = 0;
- newrow[1] = "Avinash";
- tempTable.Rows.Add(newrow);
-
- newrow = tempTable.NewRow();
- newrow[0] = 1;
- newrow[1] = "Kavita";
- tempTable.Rows.Add(newrow);
-
- Console.WriteLine("Origenal table");
- for (int i = 0; i < tempTable.Rows.Count; i++)
- {
- Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
- }
-
- Console.WriteLine("\nModified table");
- for (int i = 0; i < tempTable.Rows.Count; i++)
- {
- if (tempTable.Rows[i][1].ToString() == "Kavita")
- {
- tempTable.Rows[i][1] = "gare";
- }
- Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
- }
-
- Console.WriteLine("\nAfter deleting row from table");
- for (int i = 0; i < tempTable.Rows.Count; i++)
- {
- if (tempTable.Rows[i][1].ToString() == "gare")
- {
- tempTable.Rows[i].Delete();
- }
- }
- for (int i = 0; i < tempTable.Rows.Count; i++)
- {
- Console.WriteLine(tempTable.Rows[i][0].ToString() + "--->" + tempTable.Rows[i][1].ToString());
- }
- Console.ReadLine();
- }
- }
- }
OUTPUT
Original table
0--->Avinash
1--->Kavita
Modified table
0--->Avinash
1--->gare
After deleting row from table
0--->Avinash