Search code examples
c#postbackviewstate

C# Viewstate - cant retrieve table


I have a datatable containing file paths which I am passing via viewstate (referencing, via a linkbutton, an index in this table), wanting to then use the path from the table to construct a HTTP filetransfer. (So 3 cols; name, path and index)

I am unable to successfully retrieve the datatable once saved in viewstate;

   ViewState["varFiles"] = filedata;

(When page is originally constructed, then after postback:)

if (!IsPostBack) { SetupSession(); newpopfiles(); }
    else { { if (ViewState["varFiles"] != null) { DataTable filedata = new DataTable(); filedata = (DataTable)Session["varFiles"]; } } }

From what I understand this should pull back filedata as a table in exactly the same form as before postback. Is this correct?

When subsequently referencing the table I get a null reference exception. Any ideas?

Many thanks, Dan


Solution

  • It sounds like you're almost there, just need to be a bit more consistent with using the same storage mechanism :)

    The bit to save the DataTable into your session, probably in OnInit() or PageLoad():

    DataTable myDataTable = //... fill it in somehow
    Session["varFiles"] = myDataTable;
    

    The bit to read the DataTable after postback:

    if (!IsPostBack)
    {
        SetupSession();
        newpopfiles();
    }
    else
    {
        DataTable filedata = Session["varFiles"] as DataTable;
        if (filedata != null)
        {
            //... do something
        }
    }