数据表 - > Gridview在添加行时通过回发持久化

时间:2011-07-30 10:55:41

标签: c# asp.net gridview viewstate

我目前手动将数据添加到数据表中,然后一次将数据表绑定到一行gridview。但是,尝试添加新行时的每个回发都会覆盖原始行,因为每次都会创建并绑定新的数据表。

如何在View状态中保留数据表并添加到它,绑定,然后再次保存,以便我可以继续向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();

    }
}

1 个答案:

答案 0 :(得分:0)

您可以将数据表存储在ViewState中,如:

 ViewState["dt"] = dt; // Store it in viewstate

然后您可以从View State访问它,如下所示:

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();
}
}