将新行添加到GridView [英] Add New Rows to GridView
问题描述
我在页面上和 button_OnClick
事件上都有一个 GridView
,我想向网格中添加新行.
I have a GridView
on my page and on a button_OnClick
event I'm wanting to add a new row to the grid.
我可以使用以下代码向表中添加一行,效果很好,但是当我将 DataTable
绑定到网格时,所有先前的条目都会丢失.
I can add a row to the table using the following code, which works fine, but as I'm binding the DataTable
to the grid any previous entries are lost.
string selectedProduct= ddlProducts.SelectedItem.Text;
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
因此,尽管我了解为什么这会导致数据丢失,但我不确定如何解决它.
So whilst I understand why this is causing the data loss, I'm not really sure how to get around it.
如何在每次单击按钮的同时向 GridView
添加新行,同时保留先前添加的行?数据没有存储在网格本身以外的任何地方,因此没有真正的数据源.
How can I add a new row to the GridView
on each button click whilst retaining the previously added row? The data is not stored anywhere other than the grid itself, so there is no real datasource.
其中有一些选项,例如在客户端的gridview中添加行使用 Jquery
,但是我已经读到,在网格中添加/删除项目时使用它并不是一个好主意.也许那是错误的?或者有向gridview添加新行,但是那里没有太多细节.
There are options such as Add row to gridview on client side which uses Jquery
, but I have read that it isn't a great idea to use that when adding / removing items from the grid. Perhaps that is wrong? Or there is this Add new row to gridview but there isn't much detail there.
推荐答案
您需要将产品存储到ViewState(或SessionState或数据库)中,以便其可以在回发后持续存在.
You need to store the Products into ViewState (or SessionState or Database) so that it can persist on post back.
例如
private DataTable ProductDataTable
{
get { return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
protected void AddRowButton_Click(object sender, EventArgs e)
{
string selectedProduct = ddlProducts.SelectedItem.Text;
// Get the data from ViewState
DataTable dataTable = ProductDataTable;
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
// Save the data back to ViewState
ProductDataTable = dataTable;
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
这篇关于将新行添加到GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!