C# Gridview添加/删除行
如何向Gridview添加、删除和编辑多行“包含文本框” 不插入到数据库 我试过了C# Gridview添加/删除行,c#,asp.net,vb.net,gridview,C#,Asp.net,Vb.net,Gridview,如何向Gridview添加、删除和编辑多行“包含文本框” 不插入到数据库 我试过了 Gridview1.rows.add(datarow) 和删除 Gridview1.rows.remove(datarow) 但是,在不检测选定行的情况下,您可以使用下面代码中的方法进行此操作。在所示的addRow方法中,插入一个新的网格行。逻辑是我们需要将网格重新绑定到一个新的数据源,该数据源包含原始行和一个新的空行。您可以使用类似的删除方法(创建一个新的数据源,排除已删除的行,然后重新绑定网格) 删除时,
Gridview1.rows.add(datarow)
和删除
Gridview1.rows.remove(datarow)
但是,在不检测选定行的情况下,您可以使用下面代码中的方法进行此操作。在所示的
addRow
方法中,插入一个新的网格行。逻辑是我们需要将网格重新绑定到一个新的数据源,该数据源包含原始行和一个新的空行。您可以使用类似的删除方法(创建一个新的数据源,排除已删除的行,然后重新绑定网格)
删除时,请使用方法deleteRow
。我假设您在网格行中有一个id为chkDelete
的复选框控件,选中该复选框意味着需要删除该行。您可以使用deleteRow
的方法同时删除多行
如果使用以下两种方法添加行和删除行,则自动编辑的文本框将始终保留其新值,即,编辑将自动处理
做出的假设:此外,我假设网格行中除了一个复选框之外还有3个文本框。因为有3个文本框,所以在下面的方法中创建的DataTable应该包含这3个文本框的3列,并且这些列应该是字符串类型
添加一行
protected void addRow()
{
DataTable dt = new DataTable();
//add code to create columns for this data table
//only create columns for textbox data
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));
dt.Columns.Add("Column3", typeof(string));
DataRow dr = null;
//build a data source of existing rows
foreach (GridViewRow gridRow in grid1.Rows)
{
dr = dt.NewRow();
//set only text box values in new data source
//so checkbox column for row selection will be ignored
TextBox txtColumn1 = gridRow.FindControl("txtColumn1") as TextBox;
TextBox txtColumn2 = gridRow.FindControl("txtColumn2") as TextBox;
TextBox txtColumn3 = gridRow.FindControl("txtColumn3") as TextBox;
dr[0] = txtColumn1.Text;
dr[1] = txtColumn2.Text;
dr[2] = txtColumn3.Text;
dt.Rows.Add(dr);
}
//create the row in data sourec for the new grid row
dr = dt.NewRow();
dt.Rows.Add(dr);
//bind the grid view, which will now show you the new added row in addition to original rows
grd.DataSource = dt;
grd.DataBind();
}
删除行
如何构造数据行?您可以显示更多代码吗?您可以绑定到不带数据库的
DataTable
。我不建议直接操纵网格行,只操纵它绑定到的数据。
protected void deleteRow()
{
DataTable dt = new DataTable();
//add code to create column for this data table
//only set column for textbox columns
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));
dt.Columns.Add("Column3", typeof(string));
//build a data source of existing rows
foreach (GridViewRow gridRow in grid1.Rows)
{
//get whether the checkbox for deleting row is checked or not
CheckBox chkDelete = gridRow.FindControl("chkDelete") as CheckBox;
//do not add original row if it was checked to be deleted
if(!chkDelete.Checked)
{
dr = dt.NewRow();
//set only text box values in new data source
//so checkbox column for row selection will be ignored
TextBox txtColumn1 = gridRow.FindControl("txtColumn1") as TextBox;
TextBox txtColumn2 = gridRow.FindControl("txtColumn2") as TextBox;
TextBox txtColumn3 = gridRow.FindControl("txtColumn3") as TextBox;
dr[0] = txtColumn1.Text;
dr[1] = txtColumn2.Text;
dr[2] = txtColumn3.Text;
dt.Rows.Add(dr);
}
}
//bind the grid view, which will now NOT have the deleted rows
grd.DataSource = dt;
grd.DataBind();
}