0

I'm using GridView in ASP.NET, after editing the columns and pressing a button I want to get the whole GridView back to a DataTable or a List, how can I do it?

<asp:GridView ID="FireFighters" runat="server" AutoGenerateColumns="false"
OnRowDataBound="FireFighters_RowDataBound">

After rendering the page the DataSource is null.

alundy
  • 857
  • 8
  • 22
Tomer Oszlak
  • 245
  • 1
  • 4
  • 9
  • possible duplicate of [How can I export a GridView.DataSource to a datatable or dataset?](http://stackoverflow.com/questions/785799/how-can-i-export-a-gridview-datasource-to-a-datatable-or-dataset) – Mahesh Mar 24 '15 at 17:59
  • @CoderofCode its not like that, after the page render the DataSource is null. – Tomer Oszlak Mar 24 '15 at 18:10

1 Answers1

0

You can't get a data source back out of a web control once it's been bound and rendered. Unlike applications that you may be accustomed to programming the web is stateless and it will not persist data unless you implement that by using Session or ViewState.

In a typical example you would have an underlying data set that you are binding to the GridView, at the same time you can store it in ViewState. Any changes to the grid by the user need to trigger something to make changes to the underlying data set and then you rebind the control to that data set. There are other ways of doing this, but the point is that you have to track the changes.

Here's a rudimentary example of the above using ViewState:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        InitialDataLoad();
}

private void InitialDataLoad()
{
    var dt = new DataTable();
    dt.Columns.Add("SomeData");

    var dr = dt.NewRow();
    dr[0] = "some initial data here";
    dt.Rows.Add(dr);

    GridView1.DataSource = dt;
    GridView1.DataBind();

    ViewState["dt"] = dt;
}

protected void Button1_Click(object sender, EventArgs e)
{
    // adds a row

    var dt = ViewState["dt"] as DataTable;

    if (dt != null)
    {
        var dr = dt.NewRow();
        dr[0] = "some more data here";
        dt.Rows.Add(dr);

        GridView1.DataSource = dt;
        GridView1.DataBind();

        ViewState["dt"] = dt;
    }
}
alundy
  • 857
  • 8
  • 22