Search code examples
asp.netdatatableado.netviewstate

store datatable into viewstate in asp.net


I've created a DataTable _dt and added columns like below

_dt.Columns.Add("INDATE", typeof(string));
_dt.Columns.Add("INTIME", typeof(string));
_dt.Columns.Add("OUTTIME", typeof(string));
_dt.Columns.Add("OUTDATE", typeof(string));

and I stored _dt into Viewstate:

ViewState["_table"] = _dt;

and then I added a row into that DataTable like this:

DataRow _dr = _dt.NewRow();
_dr[0] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
_dr[3] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
_dt.Rows.Add(_dr);

and bound the DataTable to a gridview successfully.

My problem is: whenever I retrieve the DataTable from Viewstate

DataTable _dtTemp = (DataTable)ViewState["_table"];

the table contains DataRow also...

I don't want the dataRow.. I want table with column field only.


Solution

  • The DataTable object instance stored in the ViewState is the same object instance that you use when adding rows. So, whatever you do with it will be seen when you retrieve it the next time

    You could use the Clone method on your original datatable stored in the ViewState and add rows to this clone. In this way you will have two distinct objects and adding rows to the second doesn't affect the first

    ViewState["_table"] = _dt;
    DataTable temp = _dt.Clone();
    DataRow _dr = temp.NewRow();
    _dr[0] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
    _dr[3] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
    temp.Rows.Add(_dr);
    
    ....
    
    DataTable temp = (ViewState["_table"] as DataTable).Clone();
    ....