5
votes

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();
        }
    }
}
1
Store some value of the button in the viewstate, not the object itself and recreate it from state on the next page load. Alternatively, the Session object can store object references just fine, and less with overhead to the client.asawyer
How do i save the state of the buttons between each postback..since all their events are gone between postbacks :(... when i press a button after a postback no eventhanlder method is triggeredDmitry Makovetskiyd

1 Answers

6
votes

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
}