views:

41

answers:

1

I have created a composite control that changes the controls in it based on the value of one of it's properties called "Type". The intent is that once this "Type" property is set, it is not changed again for the life of the control, so the controls rendered as a result of the value of the "Type" property should not change.

I have overridden the LoadViewState and SaveViewState methods as recommended on by many internet posts, but I am still getting an error about "Failed to Load ViewState". The control will render appropriately on the first load, but once any postback is made, it generates the "Failed to Load ViewState" error.

Here is part of the code for the composite control:

    [Serializable]
internal enum SearchPanelControlType
{
    Label,
    DropDownList,
    TextBox
}
[Serializable]
internal class SearchGridViewStateObject<T> where T : Bll.BaseCriteria
{
    public T mySearchCriteria { get; set; }
    public SearchGridType myType { get; set; }
    public int myNumberOfChildrenPerRow { get; set; }
    public object myBaseViewState { get; set; }

    public SearchGridViewStateObject(T searchCriteria, SearchGridType type, int numberOfChildrenPerRow, object baseViewState)
    {
        mySearchCriteria = searchCriteria;
        myType = type;
        myNumberOfChildrenPerRow = numberOfChildrenPerRow;
        myBaseViewState = baseViewState;
    }
}
[Themeable(true)]
[Serializable]
public class SearchGrid<T> : CompositeControl
     where T : Bll.BaseCriteria
{
    #region Constructor
    public SearchGrid()
    {
    }
    #endregion

    #region Private Fields
    private MyCompanygridview myGridView;
    private ObjectDataSource myObjectDataSource;
    private Panel mySearchParametersPanel;
    private Button mySearchButton;
    private Button myClearSearchCriteriaButton;
    private T mySearchCriteria;
    //private SearchGridType myType = SearchGridType.Account;
    private SearchGridType myType;
    private int myNumberOfChildrenPerRow = 2;
    private MyCompanygridviewSelectionType mySelectionType = MyCompanygridviewSelectionType.None;
    private int mySelectColumnIndex = 0;
    private int myPageSize = 10;
    private int myPageIndex = 0;
    private string myGridViewCssClass;
    private string myCustomPagerButtonCssClass;
    private string myCustomPagerTextBoxCssClass;
    private string myRowCssClass;
    private string myEmptyDataRowCssClass;
    private string myPagerCssClass;
    private string mySelectedRowCssClass;
    private string myHeaderCssClass;
    private string myAlternatingRowCssClass;
    private string myDisabledRowCssClass;
    private List<Guid> myGridViewDisabledValues = new List<Guid>();
    private List<Guid> myGridViewSelectedValues = new List<Guid>();
    private GridLines myGridLines = GridLines.None;
    private string mySearchPanelButtonCssClass;
    private string mySearchPanelTextBoxCssClass;
    private string mySearchPanelDropDownListCssClass;
    private string mySearchPanelLabelCssClass;



    #endregion

    #region Public Properties
    /// <summary>
    /// Gets or sets the search criteria.
    /// </summary>
    /// <value>The search criteria.</value>
    public T SearchCriteria
    {
        get
        {
            return mySearchCriteria;
        }
        set
        {
            if (value != mySearchCriteria)
            {
                mySearchCriteria = value;
                this.ChildControlsCreated = false;
                this.EnsureChildControls();
            }
        }
    }
    /// <summary>
    /// Gets or sets the type of items that should be shown in the gridview.
    /// </summary>
    /// <summary>
    /// Gets or sets the type of items that should be shown in the gridview.
    /// </summary>
    [Category("SearchGrid"),
    Description("Gets or sets the type of items that should be shown in the grid view."),
    DefaultValue(null)]
    public SearchGridType Type
    {
        get
        {
            return myType;
        }
        set
        {
            if (value != myType)
            {
                myType = value;
                this.ChildControlsCreated = false;
                this.EnsureChildControls();
            }
        }

    }
    [DefaultValue(MyCompanygridviewSelectionType.None),
    Category("SearchGrid"),
    Description("Indicates whether to use multiselection mode, single selection mode, or no selection mode.")]
    public MyCompanygridviewSelectionType SelectionType
    {
        get
        {
            return mySelectionType;
        }
        set
        {
            mySelectionType = value;
        }
    }
    #endregion
    #region Overridden Methods
    protected override void LoadViewState(object savedState)
    {
        SearchGridViewStateObject<T> vsObject = savedState as SearchGridViewStateObject<T>;
        mySearchCriteria = vsObject.mySearchCriteria;
        myType = vsObject.myType;
        myNumberOfChildrenPerRow = vsObject.myNumberOfChildrenPerRow;

        ClearChildViewState();
        this.ChildControlsCreated = false;
        this.EnsureChildControls();

        base.LoadViewState(vsObject.myBaseViewState);
    }
    protected override object SaveViewState()
    {
        SearchGridViewStateObject<T> vsObject = new SearchGridViewStateObject<T>(mySearchCriteria, myType, myNumberOfChildrenPerRow, base.SaveViewState());
        return vsObject;
    }
    protected override void RecreateChildControls()
    {
        EnsureChildControls();
    }
    protected override void CreateChildControls()
    {
        SearchGridParser parser = SearchGridParserFactory.GetParser(this.myType);

        Controls.Clear();

        //Define the Search Parameters Panel
        mySearchParametersPanel = new Panel();
        mySearchParametersPanel.ID = "spp" + Enum.GetName(typeof(SearchGridType), this.myType);
        mySearchParametersPanel.DefaultButton = "btnSearch";
        mySearchParametersPanel.ScrollBars = ScrollBars.None;
        parser.CreateSearchPanelControls(ref mySearchParametersPanel, CreateSearchPanelStyleDictionary());


        //Define Buttons
        mySearchButton = new Button();
        mySearchButton.ID = "btnSearch";
        mySearchButton.Text = "Search";
        mySearchButton.CausesValidation = false;
        mySearchButton.UseSubmitBehavior = false;
        mySearchButton.Click += new EventHandler(mySearchButton_Click);
        if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
        {
            mySearchButton.CssClass = mySearchPanelButtonCssClass;
        }

        myClearSearchCriteriaButton = new Button();
        myClearSearchCriteriaButton.ID = "btnClearSearchCriteria";
        myClearSearchCriteriaButton.Text = "Clear Search Criteria";
        myClearSearchCriteriaButton.CausesValidation = false;
        myClearSearchCriteriaButton.UseSubmitBehavior = false;
        myClearSearchCriteriaButton.Click += new EventHandler(myClearSearchCriteriaButton_Click);
        if (!string.IsNullOrEmpty(mySearchPanelButtonCssClass))
        {
            myClearSearchCriteriaButton.CssClass = mySearchPanelButtonCssClass;
        }

        mySearchParametersPanel.Controls.Add(mySearchButton);
        mySearchParametersPanel.Controls.Add(myClearSearchCriteriaButton);

        // Define the GridView
        myGridView = new MyCompanygridview();
        myGridView.ID = "gv" + Enum.GetName(typeof(SearchGridType), this.myType);
        myGridView.AutoGenerateColumns = false;
        myGridView.DataKeyNames = new string[] { "ID" };
        myGridView.DataSourceID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
        myGridView.AllowSorting = true;
        myGridView.Width = new System.Web.UI.WebControls.Unit("100%");
        myGridView.AllowPaging = true;
        myGridView.EnableCustomPager = true;
        myGridView.Sorted += new EventHandler(myGridView_Sorted);
        myGridView.PageIndexChanged += new EventHandler(myGridView_PageIndexChanged);
        myGridView.PageSizeChanged += new EventHandler(myGridView_PageSizeChanged);
        myGridView.PageSizeChanging += new EventHandler(myGridView_PageSizeChanging);
        myGridView.SelectionType = this.mySelectionType;
        myGridView.SelectColumnIndex = this.mySelectColumnIndex;
        myGridView.PageSize = this.myPageSize;
        myGridView.PageIndex = this.myPageIndex;
        myGridView.CssClass = this.myGridViewCssClass;
        myGridView.CustomPagerButtonCssStyle = this.myCustomPagerButtonCssClass;
        myGridView.CustomPagerTextBoxCssStyle = this.myCustomPagerTextBoxCssClass;
        myGridView.RowStyle.CssClass = this.myRowCssClass;
        myGridView.EmptyDataRowStyle.CssClass = this.myEmptyDataRowCssClass;
        myGridView.PagerStyle.CssClass = this.myPagerCssClass;
        myGridView.SelectedRowStyle.CssClass = this.mySelectedRowCssClass;
        myGridView.HeaderStyle.CssClass = this.myHeaderCssClass;
        myGridView.AlternatingRowStyle.CssClass = this.myAlternatingRowCssClass;
        myGridView.DisabledRowCssClass = this.myDisabledRowCssClass;
        myGridView.DisabledValues = this.myGridViewDisabledValues;
        myGridView.SelectedValues = this.myGridViewSelectedValues;
        myGridView.GridLines = this.myGridLines;
        parser.CreateGridViewColumns(ref myGridView);


        // Define the object data source
        myObjectDataSource = new ObjectDataSource();
        myObjectDataSource.ID = "ods" + Enum.GetName(typeof(SearchGridType), this.myType);
        myObjectDataSource.OldValuesParameterFormatString = "original_{0}";
        myObjectDataSource.SelectMethod = "GetList";
        myObjectDataSource.SelectCountMethod = "SelectCountForGetList";
        myObjectDataSource.TypeName = "MyCompany.DCO.MyProject.Bll." + Enum.GetName(typeof(SearchGridType), this.myType) + "Manager";
        myObjectDataSource.EnablePaging = true;
        myObjectDataSource.StartRowIndexParameterName = "startRowIndex";
        myObjectDataSource.MaximumRowsParameterName = "maximumRows";
        myObjectDataSource.SortParameterName = "SortExpression";
        myObjectDataSource.Selecting += new ObjectDataSourceSelectingEventHandler(myObjectDataSource_Selecting);
        myObjectDataSource.Selected += new ObjectDataSourceStatusEventHandler(myObjectDataSource_Selected);


        // Add the defined controls
        this.Controls.Add(myObjectDataSource);
        this.Controls.Add(myGridView);
        this.Controls.Add(mySearchParametersPanel);

        parser.SetSearchPanelControls<T>(this.mySearchCriteria, ref mySearchParametersPanel);

    }

    protected override void Render(HtmlTextWriter writer)
    {
        AddAttributesToRender(writer);

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        mySearchParametersPanel.RenderControl(writer);
        writer.RenderBeginTag(HtmlTextWriterTag.Br);
        writer.RenderEndTag();

        myGridView.RenderControl(writer);
        writer.RenderBeginTag(HtmlTextWriterTag.Br);
        writer.RenderEndTag();

        myObjectDataSource.RenderControl(writer);
        writer.RenderEndTag();
    }
    #endregion

}

Here is the code for the "parser" file that creates the custom controls:

    class SearchGridParser_ApplicationFunction : SearchGridParser
{
    internal override void CreateGridViewColumns(ref MyCompanygridview myGridView)
    {
        // Link Column
        HyperLinkField linkColumn = new HyperLinkField();
        linkColumn.Text = "Edit";
        linkColumn.HeaderText = "ID";
        linkColumn.DataNavigateUrlFields = new string[] { "ID" };
        linkColumn.DataNavigateUrlFormatString = "~/AddEdit/ApplicationFunction/default.aspx?Action=Edit&ID={0}";
        myGridView.Columns.Add(linkColumn);

        // Name Column
        BoundField nameColumn = new BoundField();
        nameColumn.DataField = "Name";
        nameColumn.HeaderText = "Name";
        nameColumn.SortExpression = "Name";
        myGridView.Columns.Add(nameColumn);

        // Description Column
        BoundField descriptionColumn = new BoundField();
        descriptionColumn.DataField = "Description";
        descriptionColumn.HeaderText = "Description";
        descriptionColumn.SortExpression = "Description";
        myGridView.Columns.Add(descriptionColumn);

        // Business Criticality Column
        TemplateField businessCriticalityColumn = new TemplateField();
        businessCriticalityColumn.SortExpression = "BusinessCriticality";
        businessCriticalityColumn.HeaderText = "Criticality";
        businessCriticalityColumn.ItemTemplate = new LabelColumnGridViewTemplate(ListItemType.Item, "BusinessCriticality", "Name");
        myGridView.Columns.Add(businessCriticalityColumn);

        // Disabled Column
        CheckBoxField disabledColumn = new CheckBoxField();
        disabledColumn.DataField = "DisabledFlg";
        disabledColumn.HeaderText = "Disabled";
        disabledColumn.SortExpression = "DisabledFlg";
        myGridView.Columns.Add(disabledColumn);

        // Agencies Column
        TemplateField agenciesColumn = new TemplateField();
        agenciesColumn.HeaderText = "Agencies";
        agenciesColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Agencies", "Agency.Abbreviation");
        myGridView.Columns.Add(agenciesColumn);

        // Applications Column
        TemplateField applicationsColumn = new TemplateField();
        applicationsColumn.HeaderText = "Applications";
        applicationsColumn.ItemTemplate = new ChildObjectsGridViewTemplate(ListItemType.Item, 2, "Applications", "Application.Name");
        myGridView.Columns.Add(applicationsColumn);
    }

    internal override void CreateSearchPanelControls(ref Panel myPanel, Dictionary<SearchPanelControlType, string> myStyleDictionary)
    {
        if (myStyleDictionary == null)
        {
            myStyleDictionary = new Dictionary<SearchPanelControlType, string>();
        }

        // Title
        Literal myTitleStart = new Literal();
        myTitleStart.Text = "<h4>";

        Label myTitle = new Label();
        myTitle.Text = "Application Function:";
        myTitle.ID = "lblTitle";

        Literal myTitleEnd = new Literal();
        myTitleEnd.Text = "</h4>";



        // Begin Table
        Table myTable = new Table();
        myTable.ID = "myTable";

        // Create First Row
        TableRow myTableRow1 = new TableRow();
        myTableRow1.ID = "myTableRow1";

        // Search by Name
        TableCell myNameLabelTableCell = new TableCell();
        myNameLabelTableCell.ID = "myNameLabelTableCell";
        Label myNameLabel = new Label();
        myNameLabel.ID = "lblName";
        myNameLabel.Text = "Name:";
        myNameLabel.AssociatedControlID = "txtName";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
        {
            myNameLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
        }
        myNameLabelTableCell.Controls.Add(myNameLabel);
        myTableRow1.Cells.Add(myNameLabelTableCell);

        TableCell myNameUserInputTableCell = new TableCell();
        myNameUserInputTableCell.ID = "myNameUserInputTableCell";
        TextBox myNameTextBox = new TextBox();
        myNameTextBox.ID = "txtName";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.TextBox))
        {
            myNameTextBox.CssClass = myStyleDictionary[SearchPanelControlType.TextBox];
        }
        myNameUserInputTableCell.Controls.Add(myNameTextBox);
        myTableRow1.Cells.Add(myNameUserInputTableCell);


        // Search by Agency
        TableCell myAgencyLabelTableCell = new TableCell();
        myAgencyLabelTableCell.ID = "myAgencyLabelTableCell";
        Label myAgencyLabel = new Label();
        myAgencyLabel.ID = "lblAgency";
        myAgencyLabel.Text = "Agency:";
        myAgencyLabel.AssociatedControlID = "ddlAgency";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
        {
            myAgencyLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
        }
        myAgencyLabelTableCell.Controls.Add(myAgencyLabel);
        myTableRow1.Cells.Add(myAgencyLabelTableCell);

        TableCell myAgencyUserInputTableCell = new TableCell();
        myAgencyUserInputTableCell.ID = "myAgencyUserInputTableCell";
        DropDownList<AgencyCriteria> myAgencyDDL = new DropDownList<AgencyCriteria>();
        myAgencyDDL.Type = DropDownListType.Agency;
        myAgencyDDL.ID = "ddlAgency";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
        {
            myAgencyDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
        }
        myAgencyDDL.DisplayDisabled = true;
        myAgencyDDL.EnableAnyOption = true;
        myAgencyDDL.DataBind();
        myAgencyUserInputTableCell.Controls.Add(myAgencyDDL);
        myTableRow1.Cells.Add(myAgencyUserInputTableCell);


        myTable.Rows.Add(myTableRow1);

        // Create Second row
        TableRow myTableRow2 = new TableRow();
        myTableRow2.ID = "myTableRow2";


        // Search by BusinessCriticality
        TableCell myBusinessCriticalityLabelTableCell = new TableCell();
        myBusinessCriticalityLabelTableCell.ID = "myBusinessCriticalityLabelTableCell";
        Label myBusinessCriticalityLabel = new Label();
        myBusinessCriticalityLabel.ID = "lblBusinessCriticality";
        myBusinessCriticalityLabel.Text = "Criticality:";
        myBusinessCriticalityLabel.AssociatedControlID = "ddlBusinessCriticality";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
        {
            myBusinessCriticalityLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
        }
        myBusinessCriticalityLabelTableCell.Controls.Add(myBusinessCriticalityLabel);
        myTableRow2.Cells.Add(myBusinessCriticalityLabelTableCell);

        TableCell myBusinessCriticalityUserInputTableCell = new TableCell();
        myBusinessCriticalityUserInputTableCell.ID = "myBusinessCriticalityUserInputTableCell";
        DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = new DropDownList<LookupCodeCriteria>();
        myBusinessCriticalityDDL.Type = DropDownListType.LookupCode;
        myBusinessCriticalityDDL.ID = "ddlBusinessCriticality";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
        {
            myBusinessCriticalityDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
        }
        myBusinessCriticalityDDL.DisplayDisabled = true;
        myBusinessCriticalityDDL.EnableAnyOption = true;
        LookupCodeCriteria myBusinessCriticalityCriteria = new LookupCodeCriteria();
        myBusinessCriticalityCriteria.Type = LookupCodeType.BusinessCriticality;
        myBusinessCriticalityDDL.OtherCriteria = myBusinessCriticalityCriteria;
        myBusinessCriticalityDDL.DataBind();
        myBusinessCriticalityUserInputTableCell.Controls.Add(myBusinessCriticalityDDL);
        myTableRow2.Cells.Add(myBusinessCriticalityUserInputTableCell);

        // Search by DisabledFlg
        TableCell myDisabledFlgLabelTableCell = new TableCell();
        myDisabledFlgLabelTableCell.ID = "myDisabledFlgLabelTableCell";
        Label myDisabledFlgLabel = new Label();
        myDisabledFlgLabel.ID = "lblDisabledFlg";
        myDisabledFlgLabel.Text = "Disabled:";
        myDisabledFlgLabel.AssociatedControlID = "ddlDisabledFlg";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.Label))
        {
            myDisabledFlgLabel.CssClass = myStyleDictionary[SearchPanelControlType.Label];
        }
        myDisabledFlgLabelTableCell.Controls.Add(myDisabledFlgLabel);
        myTableRow2.Cells.Add(myDisabledFlgLabelTableCell);

        TableCell myDisabledFlgUserInputTableCell = new TableCell();
        myDisabledFlgUserInputTableCell.ID = "myDisabledFlgUserInputTableCell";
        YesNoAnyDropDownList myDisabledFlgDDL = new YesNoAnyDropDownList();
        myDisabledFlgDDL.ID = "ddlDisabledFlg";
        if (myStyleDictionary.ContainsKey(SearchPanelControlType.DropDownList))
        {
            myDisabledFlgDDL.CssClass = myStyleDictionary[SearchPanelControlType.DropDownList];
        }
        myDisabledFlgDDL.DataBind();
        myDisabledFlgUserInputTableCell.Controls.Add(myDisabledFlgDDL);
        myTableRow2.Cells.Add(myDisabledFlgUserInputTableCell);

        myTable.Rows.Add(myTableRow2);


        myPanel.Controls.Add(myTitleStart);
        myPanel.Controls.Add(myTitle);
        myPanel.Controls.Add(myTitleEnd);
        myPanel.Controls.Add(myTable);
    }

    internal override void FillSearchCriteria<T>(T myCriteria, ref Panel myPanel)
    {
        ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
        if (myCriteria != null)
        {
            derivedCriteria = myCriteria as ApplicationFunctionCriteria;
        }

        // Name
        TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
        if (!string.IsNullOrEmpty(myNameTextBox.Text.Trim()))
        {
            derivedCriteria.Name = myNameTextBox.Text.Trim();
        }
        else
        {
            derivedCriteria.Name = string.Empty;
        }

        // AgencyID
        DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
        Guid myAgencyID;
        if (myAgencyDDL.SelectedValue.TryParseGuid(out myAgencyID))
        {
            derivedCriteria.AgencyID = myAgencyID;
        }
        else
        {
            derivedCriteria.AgencyID = null;
        }

        // BusinessCriticalityID
        DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
        Guid myBusinessCriticalityID;
        if (myBusinessCriticalityDDL.SelectedValue.TryParseGuid(out myBusinessCriticalityID))
        {
            derivedCriteria.BusinessCriticalityID = myBusinessCriticalityID;
        }
        else
        {
            derivedCriteria.BusinessCriticalityID = null;
        }

        // DisabledFlg
        YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
        bool myDisabledFlg;
        if (bool.TryParse(myDisabledFlgDDL.SelectedValue, out myDisabledFlg))
        {
            derivedCriteria.DisabledFlg = myDisabledFlg;
        }
        else
        {
            derivedCriteria.DisabledFlg = null;
        }

    }

    internal override void SetSearchPanelControls<T>(T myCriteria, ref Panel myPanel)
    {
        ApplicationFunctionCriteria derivedCriteria = new ApplicationFunctionCriteria();
        if (myCriteria != null)
        {
            derivedCriteria = myCriteria as ApplicationFunctionCriteria;
        }

        // Name
        TextBox myNameTextBox = (TextBox)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myNameUserInputTableCell").FindControl("txtName");
        myNameTextBox.Text = derivedCriteria.Name;

        // AgencyID
        DropDownList<AgencyCriteria> myAgencyDDL = (DropDownList<AgencyCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow1").FindControl("myAgencyUserInputTableCell").FindControl("ddlAgency");
        if (derivedCriteria.AgencyID.HasValue)
        {
            myAgencyDDL.SelectedValue = derivedCriteria.AgencyID.ToString();
        }
        else
        {
            myAgencyDDL.SelectedValue = "0";
        }

        // BusinessCriticalityID
        DropDownList<LookupCodeCriteria> myBusinessCriticalityDDL = (DropDownList<LookupCodeCriteria>)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myBusinessCriticalityUserInputTableCell").FindControl("ddlBusinessCriticality");
        if (derivedCriteria.BusinessCriticalityID.HasValue)
        {
            myBusinessCriticalityDDL.SelectedValue = derivedCriteria.BusinessCriticalityID.ToString();
        }
        else
        {
            myBusinessCriticalityDDL.SelectedValue = "0";
        }

        // DisabledFlg
        YesNoAnyDropDownList myDisabledFlgDDL = (YesNoAnyDropDownList)myPanel.FindControl("myTable").FindControl("myTableRow2").FindControl("myDisabledFlgUserInputTableCell").FindControl("ddlDisabledFlg");
        if (derivedCriteria.DisabledFlg.HasValue)
        {
            myDisabledFlgDDL.SelectedValue = derivedCriteria.DisabledFlg.ToString();
        }
        else
        {
            myDisabledFlgDDL.SelectedValue = "any";
        }

    }
}

Here is the code on the aspx page I am using to test the control:

    <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

And the codebehind:

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CustomWebControls.SearchGrid<AccountCriteria> myAppFuncGrid = new      MyCompany.DCO.MyProject.CustomWebControls.SearchGrid<AccountCriteria>();
        myAppFuncGrid.Type = MyCompany.DCO.MyProject.CustomWebControls.SearchGridType.Account;
        myAppFuncGrid.SelectionType = MyCompany.DCO.Library.WebControls.MyCompanygridviewSelectionType.Multiple;
        myAppFuncGrid.PageSize = 3;
        PlaceHolder1.Controls.Add(myAppFuncGrid);
    }
}

I've tried only putting the control in if (!Page.IsPostBack) as well, but then it just doesn't even display the control at all on Postback. What am I doing wrong?

UPDATE: So I added this to the composite control:

protected override void OnInit(EventArgs e) 
{ 
 this.CreateChildControls(); base.OnInit(e); 
} 

And now I no longer get the "failed to load viewstate" error, but it seems that the viewstate of the child controls is not saved across postbacks. One of the controls in my composite control is a gridview with paging enabled and when clicking on next page it will go to page two, but never to page 3 or 4 or so on. But it will go to "last page", "first page" without a problem. But Next Page and Previous Page do no work correctly, but it doesn't throw an error either. Ideas?

A: 

When adding your control dynamically to your page, try overriding OnInit or CreateChildControls and doing it in there.

Viewstate is loaded in the pre-load stage and therefore it cannot load viewstate for your controls as they dont yet exist...

Richard Friend
I've already tried adding the control in the OnInit method of the page, but it behaves the same way.
Amanda Myer
Also, I have put the control on the page declaratively, and it has the same behavior.
Amanda Myer