开发者

Datatable -> Gridview persisting through postback when adding rows

I am currently manually adding data to a datatable and then binding the datatable to a gridview one row at a time. However each postback when attempting to add a new row is overwriting the original row because a new datatable is created and bound each time.

How can I preserve the datatable in the View state and add to it, bind, and then preserve again so I can keep adding rows to the gridview? I am not familiar with the View State at all; I only know that it is what I want from googling around.

    <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.Co开发者_运维百科lumns.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();

    }
}


You can store the datatable in ViewState like:

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

Then you can access it from View State as follows:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜