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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With