删除网格视图中的特定行,而不会丢失以前的数据



我想创建一个动态网格视图,其中包含行号、两个文本框和一个用于删除行的链接按钮。在页面加载时,网格由 6 行创建。

我只想隐藏前 4 行的链接按钮以进行删除。 并在用户删除最后两行之一时设置前面的数据。

这些是我用于设置以前的数据和删除行的函数。

private void SetInitialRows() {
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value 
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value  
dr = dt.NewRow();
for(int i = 1; i < 7; i++)
{ 
dr["RowNumber"] = i;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
}
//Store the DataTable in ViewState for future reference 
ViewState["CurrentTable"] = dt;
//Bind the Gridview 
Gridview1.DataSource = dt;
Gridview1.DataBind();
}

private void SetPreviousData() {
int rowIndex = 0;
if (ViewState["CurrentTable"] != null) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0) {
for (int i = 0; i < dt.Rows.Count; i++) {
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");               
if (i < dt.Rows.Count - 1) {
//Assign the value from DataTable to the TextBox 
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();                  
}
rowIndex++;
}
}
}
}
protected void LinkDelete_Click(object sender, EventArgs e) {
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1) {
if (gvRow.RowIndex < dt.Rows.Count - 1) {
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}

一种方法是将更改的数据复制到另一个数据表。如果需要保存更改或执行验证,这使其变得简单,而不会影响原始数据。

最新更新