C# 删除行后的DataTable递减列值
嗨。我有一个C# 删除行后的DataTable递减列值,c#,asp.net,datagridview,datatable,C#,Asp.net,Datagridview,Datatable,嗨。我有一个DataTable其中一列设置为AutoIncrement为true。基本上,我向DataTable添加一些文本框值,然后将其绑定到网格视图。我试图实现的是,如果我从网格视图中删除一行,那么还需要删除DataTable中的行,并减少主键列 DataTable是这样声明的private DataTable=new DataTable()和代码为: DataColumn promoDetailsID = new DataColumn(); promoDetailsID.ColumnNam
DataTable
其中一列设置为AutoIncrement
为true。基本上,我向DataTable添加一些文本框值,然后将其绑定到网格视图。我试图实现的是,如果我从网格视图中删除一行,那么还需要删除DataTable中的行,并减少主键列
DataTable是这样声明的private DataTable=new DataTable()代码>和代码为:
DataColumn promoDetailsID = new DataColumn();
promoDetailsID.ColumnName = "promoDetailsID";
promoDetailsID.DataType = System.Type.GetType("System.Int32");
promoDetailsID.AutoIncrement = true;
promoDetailsID.AutoIncrementSeed = 1;
promoDetailsID.AutoIncrementStep = 1;
table.Columns.Add(promoDetailsID);
table.Columns.Add("StartRange", typeof(string));
table.Columns.Add("EndRange", typeof(string));
table.Columns.Add("Amount", typeof(string));
table.Columns.Add("AllocationCases", typeof(string));
table.Columns.Add("AllocationUnits", typeof(string));
if (ViewState["dtTable"] != null)
{
table = (DataTable)ViewState["dtTable"];
}
table.Rows.Add(null,TxtStartRange.Text.Trim(), TxtEndRange.Text.Trim(), TxtAllocationAmount.Text.Trim(), TxtAllocationCases.Text.Trim(), TxtAllocationUnits.Text.Trim());
grdPromotions.DataSource = table;
grdPromotions.DataBind();
ViewState["dtTable"] = table;
这是我试图从网格中删除行时的代码
protected void grdPromotions_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (ViewState["dtTable"] != null)
{
table = (DataTable)ViewState["dtTable"];
int rowIndex = Convert.ToInt32(e.RowIndex);
table.Rows[e.RowIndex].Delete();
}
table.AcceptChanges();
grdPromotions.DataSource = table;
grdPromotions.DataBind();
ViewState["dtTable"] = table;
}
我没有收到任何错误,但是数据表在删除后没有更新。因为您没有使用真实的数据库,所以使用DataRow是没有意义的。delete
只会将其RowState
设置为Deleted
。您要做的是从数据表中删除该行
table.Rows.RemoveAt(e.RowIndex);
如果还要减少主键列,则必须使该列可写:
table.Columns[0].ReadOnly = false;
然后需要手动更新该值:
int counter = 0;
foreach(DataRow row in table.Rows)
{
row[0] = ++counter;
}
table.Columns[0].ReadOnly = true;
旁注:不要在ViewState
中存储DataTable
,如果需要在回发之间保存,请使用会话。会话存在于内存中,而ViewState
将被序列化并存储在呈现的html中,因此它也将被传输到客户端。不要在ViewState中存储数据表
,如果需要在回发之间保持它,请使用会话
。访问此链接。