Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Edit a row in the datatable

Tags:

c#

datatable

I have created a data table. It has 3 column Product_id, Product_name and Product_price

    Datatable table= new DataTable("Product");      table.Columns.Add("Product_id", typeof(int));     table.Columns.Add("Product_name", typeof(string));     table.Columns.Add("Product_price", typeof(string));      table.Rows.Add(1, "abc", "100");     table.Rows.Add(2, "xyz", "200"); 

Now I want to find by index, and update that row.

say for e.g.

I want to change value of Product_name column to "cde" that has the Product_id column value : 2.

like image 525
folk Avatar asked Oct 28 '13 07:10

folk


1 Answers

First you need to find a row with id == 2 then change the name so:

foreach(DataRow dr in table.Rows) // search whole table {     if(dr["Product_id"] == 2) // if id==2     {         dr["Product_name"] = "cde"; //change the name         //break; break or not depending on you     } } 

You could also try these solutions:

table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2 

Or:

DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any if(dr != null) {     dr["Product_name"] = "cde"; //changes the Product_name } 
like image 111
Tafari Avatar answered Sep 21 '22 21:09

Tafari