How to Select Data from DataTable and Update it

DataTable have a select method to select a row. This method selects a string expression by which it specifies which row you want to select. Select method spouse DataTable as like database.

First, we create a DataTable with 5 rows. Each row contains ID, NAME, and SALARY.

  1. DataTable table = new DataTable("Employee");  
  2.             table.Columns.Add(new DataColumn("ID"typeof(int)));  
  3.             table.Columns.Add(new DataColumn("NAME"typeof(string)));  
  4.             table.Columns.Add(new DataColumn("SALARY"typeof(int)));  
  5.   
  6.             table.Rows.Add(1, "AMIT",8000);  
  7.             table.Rows.Add(2, "SUMIT",10000);  
  8.             table.Rows.Add(3, "RAMESH",12000);  
  9.             table.Rows.Add(4, "ROHAN",20000);  
  10.             table.Rows.Add(5, "RAHUL",5000);  
  11.   
  12. And we find out only those record which salary less than 10000.we use following code.  
  13. DataRow[] result = table.Select("SALARY < 10000");  
  14. After find out these people and update his record (salary =25000) after this we select only those record which salary >20000  
  15. id = Convert.ToInt32(row[0]);  
  16.                 string find = "ID = '" +id + "'";  
  17.                 //find out id  
  18.                 DataRow[] resultupdate = table.Select(find);  
  19.                 //update row  
  20.                 resultupdate[0]["SALARY"] = 25000;  
  21.                 //Accept Changes  
  22.                 table.AcceptChanges();  

After update DataTable we call function AcceptChanges () if you want to reject last change made in DataTable you must be call RejectChanges ()