Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

ViewState in Dynamic Control

, 22 Apr 2009 CPOL
Maintaining ViewState while working with Dynamic Control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DynamicControl : System.Web.UI.Page
{
    private const string VIEWSTATEKEY = "ContactCount";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Set the number of default controls
            ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 2 : ViewState[VIEWSTATEKEY];
            
            //Load the contact control based on Vewstate key
            LoadContactControls();
        }
    }

    /// <summary>
    /// Load the contact control based on Vewstate key
    /// </summary>
    private void LoadContactControls()
    {
        for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
        {
            phContactDetails.Controls.Add(LoadControl("~/UserControl/ContactDetails.ascx"));
        }
    }

    /// <summary>
    /// Handels the click event of AddMore button
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        ViewState[VIEWSTATEKEY] = int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
        LoadContactControls();
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

Share

About the Author

BhadeliaImran
Team Leader Softwebsolutions INC
India India
Profiles : Code Project, ASP.NET Forums

Blog : Knowledgebase
World


Current Company : Softwebsolution
INC


User Group : Ahmedabad SQLServer UserGroup

Other : Microsoft Certified Technology Specialist (MCTS)

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141030.1 | Last Updated 22 Apr 2009
Article Copyright 2009 by BhadeliaImran
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid