如何编辑数据表中的行
我创建了一个数据表。 它有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 }
你可以找到那一行
DataRow row = table.Select("Product_id=2").FirstOrDefault();
并更新它
row["Product_name"] = "cde";
尝试SetField方法:
table.Rows[rowIndex].SetField(column, value); table.Rows[rowIndex].SetField(columnIndex, value); table.Rows[rowIndex].SetField(columnName, value);
如果数据集太大,请先按Select()选择所需的行。 它将停止进一步循环。
DataRow[] selected = table.Select("Product_id = 2")
然后遍历子集并更新
foreach (DataRow row in selected) { row["Product_price"] = ""; }
您可以像下面一样遍历DataTable并设置值
foreach(DataTable thisTable in dataSet.Tables) { foreach(DataRow row in thisTable.Rows) { row["Product_name"] = "cde"; } }
要么
thisTable.Rows[1]["Product_name"] = "cde";
希望这可以帮助
试试这个我也不是100%肯定
for( int i = 0 ;i< dt.Rows.Count; i++) { If(dt.Rows[i].Product_id == 2) { dt.Rows[i].Columns["Product_name"].ColumnName = "cde"; } }