Reputation: 2522
I’ve created a panel to store my ListBoxes, my goal is to add new Listboxes dynamically when I press the Button control on the page.
I’ve created a MyList class that inherits List class and I’ve applied the [Serializable] tag. I've applied serialized to store the object in the viewstate.
The MyList class will store all the ListBoxes dynamically created.
questions:
Do I also need to serialize the base class (List) of MyList?
public partial class _default : System.Web.UI.Page
{
MyList<ListBox> myList;
protected void Page_Load(object sender, EventArgs e)
{
myList = new MyList<ListBox>();
myList.Add(new ListBox());
Panel1.Controls.Add(myList[0]);
Button1.Click += Add_ListBox1;
}
public void Add_ListBox1(object sender, EventArgs e)
{
ListBox temp_listBox = new ListBox();
myList.Add(temp_listBox);
Panel1.Controls.Add(temp_listBox);
ViewState["ListBox_list"] = myList;
}
}
[Serializable]
public class MyList<ListBox> : List<ListBox>
{
}
page laoded before clicking:
error message after clicking button:
Upvotes: 3
Views: 3250
Reputation: 32037
Although you've marked your class [serializable], it depends on ListBox which is not serializable.
I did a little googling and found this which may help, although it looks more involved than I would expect.
Couple quick thoughts:
Dynamic content is one of the weaker spots in WebForms because, as you're seeing, the dynamic content is lost after postback, so it must be persisted and re-created in some way. In these situations, I try to and eliminate postbacks and rely more on JavaScript so the browser never gets reset... And this is one of the places where the new MVC model shines, because it isn't constantly fighting you (as the postpack model inadvertently does). Actually, this pain is one of the main things nudging us towards single page applications.
You might be better off writing your own class that contains what you care about regarding these listboxes, such as position and their contents which is hopefully just some simple strings, and serialize that instead... Then write your own code to de-serialize them into ListBoxes.
Nothing against webforms by the way, I have one open right now in another window!
Upvotes: 2