0
votes

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?

2

2 Answers

1
votes

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?

0
votes

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!