如何编辑数据表中的一行 [英] How to Edit a row in the datatable

查看:153
本文介绍了如何编辑数据表中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个数据表。它有3列 Product_id Product_name 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);

现在我想通过索引查找并更新该行。



例如说



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

解决方案

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

  foreach(Table.Rows中的DataRow dr)//搜索整个表
{
if(dr [Product_id] == 2)// if id == 2
{
dr [Product_name] =cde; //更改名称
// break;你还可以尝试这些,你还可以尝试这些解决方案:

  table.Rows [1] [Product_name] =cde//不推荐选择第二行因为我知道它有id 2 

或:

  DataRow dr = table.Select(Product_id = 2)。FirstOrDefault(); //找到id == 2的所有行,如果没有找到任何
,则选择第一个或null(如果(dr!= null)
{
dr [Product_name] =cde ; //更改Product_name
}


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
}

这篇关于如何编辑数据表中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆