Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get an exception while using a ViewState

I get this:

System.Runtime.Serialization.SerializationException

Type 'System.Web.UI.WebControls.Button' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.Serialization.SerializationException: Type 'System.Web.UI.WebControls.Button' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.

I get it when I try to save a List to a viewState and recover it in the Page_PreInit event.

I set the buttons and add them to a list that I later save to a viewState:

ViewState["Buttons"] = buttons;

Then I want to retrieve them and attach them back to their eventhandlers:

void Page_PreInit(object sender, EventArgs e)
{

    List<Button> btn = (List<Button>)ViewState["Buttons"];
    if (btn!=null)
    {
        foreach (var item in btn)
        {
            item.Width = 20;
            item.Command += obtainTopicsPerPage_Click;
            item.CommandName = tPage.ToString();
            item.Text = tPage.ToString();
        }
    }
}
like image 713
Dmitry Makovetskiyd Avatar asked Jun 15 '11 11:06

Dmitry Makovetskiyd


1 Answers

According to the exception message, System.Web.UI.WebControls.Button isn't serializable. (This isn't surprising.) In order to save something to ViewState, it has to be serializable so that its complete "self" can be written to a string and stored in the hidden form value on the page for ViewState.

Why are you trying to store Buttons in ViewState anyway? ViewState is useful for storing small values and otherwise goes-in-a-hidden-form-field stuff. But entire UI controls? What are you trying to accomplish with that?

If you just need to dynamically create Button controls based on some data from ViewState, then you should just store the minimum amount of data to make that possible and create the Buttons in the code from that data. Something like this:

List<string> btn = (List<string>)ViewState["ButtonStrings"];
foreach (var str in btn)
{
    var item = new Button();
    item.Width = 20;
    item.Command += obtainTopicsPerPage_Click;
    item.CommandName = tPage.ToString();
    item.Text = tPage.ToString();
    // some use of the str from the ViewState
    // or if all you need is a count, just store an int in ViewState and use a for loop
}
like image 99
David Avatar answered Oct 07 '22 19:10

David