You'll get better results if you bind the list in the
Init
event of the
control, rather than the page.
protected void ddlCustomers_Init(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
ddl.DataSource = SystemData.GetAllCustomers();
ddl.DataTextField = "CustomerName";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Select Customers", "-1"));
}
The reason this works is that the control's
Init
event is fired before the control starts tracking changes to its
ViewState
. As a result, rather than storing the list of items in
ViewState
, the control simply assumes that the list will be recreated every time the page is loaded.
You want to do this in the
control's Init
event rather than the page's
Init
event, due to the way the event is raised:
internal virtual void InitRecursive(Control namingContainer)
{
if (HasControls)
{
foreach (Control child in Controls)
{
child.UpdateNamingContainer(namingContainer);
child.GenerateAutomaticID();
child.Page = this.Page;
child.InitRecursive(namingContainer);
}
Controls.SetCollectionReadOnly();
}
ApplySkin(Page);
OnInit(EventArgs.Empty);
TrackViewState();
}
The
Init
event is a bubbling event; it's raised on the child controls before it's raised on the parent. By the time the page's
Init
event is raised, the control is already tracking view-state.