简体   繁体   中英

How to keep grid DataSource after PostBack

I've written a custom grid view and I want to save grid DataSource in ViewState but I got this exception

Type '<>f__AnonymousType0`7[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'ExtAspNet.Examples, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable .

Now, I want to know how can I keep the grid DataSource ?

Anything that you attempt to put in the viewstate must be decorated with the [Serializable] attribute, but because you have an anonymous type, you can't do it.

But besides that, don't do what you are trying to do, it will increase your page size considerably and unnecessarily. If anything, put your data source in Session and rebind it on postback but don't put it on viewstate.

Note, though, that putting a huge amount of data in session is not scalable or a good practice either, you have to base your decission depending on the size of your data and how much time it takes to get the data from the backend store. Have you measured how expensive it is to get the data, could you use Cache instead of Session, for example?

if you are binding your gridview datasource with a datatable you can do like this....

Declare the datatable as follows and everything will work as expected

    private string _theDataTable="theDataTable";
    private DataTable theDataTable
    {
            get
            {
                    if(ViewState[_theDataTable]==null)
                            return new DataTable();
                    return (DataTable)ViewState[_theDataTable];
            }
            set
            {
                    ViewState[_theDataTable] = value;
            }
    }

cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM