Datatable→在添加行时,Gridview通过回发保持持久化
本文关键字:持久化 Gridview 添加行 Datatable | 更新日期: 2023-09-27 18:03:55
我目前手动添加数据表,然后将数据表绑定到gridview一行。但是,每次尝试添加新行的回发都会覆盖原始行,因为每次都会创建和绑定新的数据表。
我如何保存数据表在视图状态,并添加到它,绑定,然后保存再次,所以我可以继续添加行到gridview?我对视图状态一点也不熟悉;我只知道,这是我想从谷歌周围。
<asp:DropDownList ID="DDLFirstColumn" runat="server" Style="z-index: 1; left: 11px;
top: 171px; position: absolute; height: 16px; width: 104px">
<asp:ListItem>Selection 1</asp:ListItem>
<asp:ListItem>Selection 2</asp:ListItem>
<asp:ListItem>Selection 3</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtSecondColumn" runat="server" style="z-index: 1; left: 127px; top: 169px; position: absolute; height: 22px; width: 56px"></asp:TextBox>
<asp:DropDownList ID="DDLThirdColumn" runat="server" Style="z-index: 1; left: 200px; top: 171px;
position: absolute">
<asp:ListItem>Selection 1</asp:ListItem>
<asp:ListItem>Selection 2</asp:ListItem>
<asp:ListItem>Selection 3</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btn_Add" runat="server" Style="z-index: 1; left: 345px; top: 167px;
position: absolute" Text="Add" OnClick="btn_Add_Click" />
<asp:GridView ID="GridView1" runat="server" Style="z-index: 1; left: 14px; top: 219px;
position: absolute; width: 400px">
</asp:GridView>
using System;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Add_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column 1", Type.GetType("System.String"));
dt.Columns.Add("Column 2", Type.GetType("System.String"));
dt.Columns.Add("Column 3", Type.GetType("System.String"));
dt.Columns[0].DefaultValue = DDLFirstColumn.SelectedValue;
dt.Columns[1].DefaultValue = txtSecondColumn.Text;
dt.Columns[2].DefaultValue = DDLThirdColumn.SelectedValue;
dt.Rows.Add();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
您可以像这样在ViewState中存储数据表:
ViewState["dt"] = dt; // Store it in viewstate
那么你可以从viewstate中访问它,如下所示:
DataTable dt = (DataTable)ViewState["dt"]; // Retrieving from ViewState
protected void btn_Add_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
..............
dt.Rows.Add();
ViewState["dt"] = dt; // storing datatable in ViewState
GridView1.DataSource = dt;
GridView1.DataBind();
}
}