C# 4.0 基于行和列Id替换Datatable中的单列值
我一直在MVC5应用程序中处理DataTable,有一个要求,我需要用新值替换DataTable中某行的特定列值,我已经用更新的值获得了行和列id号。但我需要一种用新值替换旧值的简单方法。 这就是我迄今为止所尝试的:C# 4.0 基于行和列Id替换Datatable中的单列值,c#-4.0,model-view-controller,datatable,C# 4.0,Model View Controller,Datatable,我一直在MVC5应用程序中处理DataTable,有一个要求,我需要用新值替换DataTable中某行的特定列值,我已经用更新的值获得了行和列id号。但我需要一种用新值替换旧值的简单方法。 这就是我迄今为止所尝试的: public ActionResult Change(int RowId, int ColId, string NewValue, string OldValue) { if (NewValue != OldValue) {
public ActionResult Change(int RowId, int ColId, string NewValue, string OldValue)
{
if (NewValue != OldValue)
{
DataTable dataTable = new DataTable();
//Here i will store value from session
dataTable = Session["Table"] as DataTable;
//Here i'll get entire Single Row record from the Data Table based on Row Id
DataRow dataRow = dataTable.Rows[RowId];
//Now i want to get column value by providing Column Id
//DataColumn dataColumn = new DataColumn("ColId");
//Here i'll store new value for that column
dataColumn = NewValue;
//Now Replace or Save new column value back to Datatable
//dataTable.Columns.Remove("ColId");
//dataTable.Columns.Add(dataColumn);
}
return View();
}
有人能帮我保存/替换数据表中行和行中该特定列的新列值吗
我用以下代码解决了这个问题:
public ActionResult Change(int RowId, int ColId, string NewValue, string OldValue)
{
if (NewValue != OldValue)
{
DataTable dataTable = new DataTable();
//Here i will store value from session
dataTable = Session["Table"] as DataTable;
//Here i'll get entire Single Row record from the Data Table based on Row Id
DataRow dataRow = dataTable.Rows[RowId];
//This is what i used to do replace value
if (Convert.ToString(dataRow[ColId]) == OldValue)
{
dataRow[ColId] = NewValue;
dataTable.AcceptChanges();
Session["Table"] = dataTable;
}
}
return View();
}
实现这一点有多种方法
- table.Rows[RowId][ColId]=NewValue(可能需要写入table.acceptchanges())