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();
}
}
}