GridView的添加/删除行
问题描述:
我怎么可以添加,删除和编辑多行 “包含文本框” 来的GridViewGridView的添加/删除行
没有插入到DB
我试图
Gridview1.rows.add(datarow)
而对于删除
Gridview1.rows.remove(datarow)
但未检测到所选行
答
您可以在下面的代码中使用该方法。在所示的addRow
方法中,插入新的网格行。逻辑是我们需要将网格重新绑定到包含原始行和新空行的新数据源。您可以使用类似的方法进行删除(创建一个删除了行的新数据源,然后重新绑定网格)。
删除时使用方法deleteRow
。我假设你在网格行中有一个复选框控件,其编号为chkDelete
,选中时表示该行需要删除。您可以使用deleteRow
的方法同时删除多行。
如果您使用以下两种方法添加行并删除行,那么编辑后的文本框会自动保留其新值,即始终保留为editing would then be automatically taken care of
。
作出的假设:此外,我假定除了复选框外,网格行中还有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();
}
删除行(S)
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();
}
你如何构建你的数据行?你能展示更多的代码吗? – lyz
您可以绑定到没有数据库的'DataTable'。我不会推荐直接操纵网格行,只是操纵它绑定的数据。 – Crowcoder