Click here to Skip to main content
15,939,243 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,

We all know the problem of very huge view state when binding the dropdownlist for example. Few weeks ago I searched for it and the solution I found was to override OnInit method. Take this for example:
protected override void OnInit(EventArgs e)
    ddlCustomers.DataSource = SystemData.GetAllCustomers();
    ddlCustomers.DataTextField = "CustomerName";
    ddlCustomers.Items.Insert(0, new ListItem("Select Customers", "-1"));

With this code the view state is only 3 to 4 lines (Well maybe because of a lot of controls I have :D )

Can some explain how this works ? I'm little bit familiar with page life cycle but just can't figure out how this works.
Updated 17-Sep-14 3:41am

1 solution

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.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)
    // Pseudo-code:
    if (HasControls)
        foreach (Control child in Controls)
            child.Page = this.Page;




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.
Share this answer
Abdallah Al-Dalleh 19-Sep-14 14:22pm    
You have my respect sir! Perfect, helpful answer! :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900