Hi, everybody. I have this problem. When I put a <asp:ListBox on a web page and populate the data in the page Page_Load event the ViewState for the control is saved and loaded (after postback) correctly. In other words the Items property of the ListBox is populated from the ViewState after the postback. However if I put this ListBox inside a UserControl, expose the Items list, and populate it with the data in the same manner (in the page Page_Load event), the data is lost after the postback. What is wrong?
Here is the code with viewstate working:
Page:
Code behind:
...
Here is the code with viewstate not working:
Page:
Code behind:
...
User control:
Code behind:
...
Here is the code with viewstate working:
Page:
Code:
<html xmlns="http://www.w3.org/1999/xhtml"> <body> <form id="MainForm" runat="server"> <asp:ListBox ID="ctrlDynList" runat="server" /> <br /> <asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" /> </form> </body> </html>
...
Code:
public partial class MultiSelect : Page {
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
ctrlDynList.Items.Add(new ListItem("One", "1"));
ctrlDynList.Items.Add(new ListItem("Two", "2"));
}
}
...
}
Page:
Code:
<%@ Register Src="~/Test/SimplePanel.ascx" TagPrefix="uc" TagName="SimplePanel" %> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form id="MainForm" runat="server"> <uc:SimplePanel ID="ctrlDynList" runat="server" /> <br /> <asp:Button ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" runat="server" /> </form> </body> </html>
...
Code:
public partial class MultiSelect : Page {
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
ctrlDynList.Items.Add(new ListItem("One", "1"));
ctrlDynList.Items.Add(new ListItem("Two", "2"));
}
else {
// The ctrlDynList.Items is empty in this case.
// It is not loaded from the viewstate like it does
// in the case when the ListBox is placed on the page (not inside a user control)
}
}
...
}
Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SimplePanel.ascx.cs" Inherits="MgScopes.MgScopesWeb.Test.SimplePanel" %> <asp:ListBox ID="ctrlListBox" runat="server" />
...
Code:
public partial class SimplePanel : UserControlBase {
protected void Page_Load(object sender, EventArgs e) {
}
public ListItemCollection Items {
get { return ctrlListBox.Items; }
}
}
...
}
Comment