我已经创建了一个数据表。它具有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(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
}
}
您也可以尝试以下解决方案:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
要么:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句