[c#] How to Edit a row in the 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.

This question is related to c# datatable

The answer is


You can find that row with

DataRow row = table.Select("Product_id=2").FirstOrDefault();

and update it

row["Product_name"] = "cde";

If your data set is too large first select required rows by Select(). it will stop further looping.

DataRow[] selected = table.Select("Product_id = 2")

Then loop through subset and update

    foreach (DataRow row in selected)
    {
        row["Product_price"] = "<new price>";
    }

Try this I am also not 100 % sure

        for( int i = 0 ;i< dt.Rows.Count; i++)
        {
           If(dt.Rows[i].Product_id == 2)
           {
              dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
           }
        }

Try the SetField method:

By passing column object :

table.Rows[rowIndex].SetField(column, value);

By Passing column index :

table.Rows[rowIndex].SetField(0 /*column index*/, value);

By Passing column name as string :

table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);

You can traverse through the DataTable like below and set the value

foreach(DataTable thisTable in dataSet.Tables)
{
    foreach(DataRow row in thisTable.Rows)
    {
        row["Product_name"] = "cde";
    }
}

OR

thisTable.Rows[1]["Product_name"] = "cde";

Hope this helps