如何编辑数据表中的行

fol*_*olk 19 c# datatable

我创建了一个数据表.它有3列Product_id,Product_nameProduct_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");
Run Code Online (Sandbox Code Playgroud)

现在我想通过索引找到并更新该行.

比如说

我想将Product_name列的值更改为具有Product_id列值的"cde" :2.

Taf*_*ari 57

首先,您需要找到id == 2的行,然后更改名称,以便:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以尝试这些解决方案:

table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Run Code Online (Sandbox Code Playgroud)

要么:

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
}
Run Code Online (Sandbox Code Playgroud)


idu*_*sun 17

你可以找到那一行

DataRow row = table.Select("Product_id=2").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

并更新它

row["Product_name"] = "cde";
Run Code Online (Sandbox Code Playgroud)

  • 尽管这适用于 OP 问题,但请注意,如果 select 返回多条记录,则此解决方案仅更新第一条记录。 (2认同)

Moh*_*res 8

尝试SetField方法:

table.Rows[rowIndex].SetField(column, value);
Run Code Online (Sandbox Code Playgroud)


e03*_*050 6

如果您的数据集太大,请先按Select()选择所需的行.它将停止进一步循环.

DataRow[] selected = table.Select("Product_id = 2")
Run Code Online (Sandbox Code Playgroud)

然后遍历子集并更新

    foreach (DataRow row in selected)
    {
        row["Product_price"] = "<new price>";
    }
Run Code Online (Sandbox Code Playgroud)