Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ViewState in Dynamic Control

4.81/5 (15 votes)
22 Apr 2009CPOL2 min read 112.5K   3.1K  
Maintaining ViewState while working with Dynamic Control

Introduction

ViewState has been always a problem while working with dynamic controls in .NET environment; many times we do not find the ViewState, and using update panel, there are lots of errors that say invalid view state.

Why are we using ViewState? Yes, we need to maintain state of controls during postback. Now think you are writing a Classic ASP application, remember how to retain control property? If yes then good, else this article will let you know how to use Classic ASP code to overcome viewstate.

Using the Code

There are very few lines of code you write to achieve this. From the introduction, people may get an idea of how to do this!

We are going to use one control which asks the Address Details for a person, we create them dynamically by clicking "Add More" button inside Place Holder control. We will set the EnableViewState to false in user control, as we no longer need to maintain viewstate of dynamic control.

ASP.NET
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ContactDetails.ascx.cs"

Inherits="UserControl_ContactDetails" EnableViewState="false" %> 

Let's load this control into PlaceHolder of an aspx page. The following method will help to load control dynamically.

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

It's a simple LoadControl statement, from ViewState [it's on aspx not of control] we are getting the number of Controls needs to be added inside phContactDetails. In PageLoad event, we have already assigned how many controls we need to show when page loads for the first time:

C#
if (!Page.IsPostBack)
{
    //Set the number of default controls
    ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 
					2 : ViewState[VIEWSTATEKEY];
    
    //Load the contact control based on Viewstate key
    LoadContactControls();
}

So far so good, but still we don't have ViewState and now let's get back to the control and write some cool Classic ASP code to get the states of control ourselves. Before we go ahead; we all know, when any control or a .NET page gets rendered, they always is a single Form having all the items which are controls, nothing else. So we will use the same practice to get the control value. Let's see how.

C#
protected void Page_Load(object sender, EventArgs e)
{
    //Retain the state of controls
    txtAddress1.Text = Request.Form[txtAddress1.UniqueID];
    txtAddress2.Text = Request.Form[txtAddress2.UniqueID];
    txtCity.Text = Request.Form[txtCity.UniqueID];
    txtFirstName.Text = Request.Form[txtFirstName.UniqueID];
    txtLastName.Text = Request.Form[txtLastName.UniqueID];
    txtZip.Text = Request.Form[txtZip.UniqueID];
}

As I just mentioned earlier, we always have Request.Form having all child controls, we are using Form item collection and UniqueID control to get the value form collection. When a control gets rendered, we can identify using ClientID on JavaScript. It also generates UniqueID which are the keys of Item collection. Let's look at a few screen shots, which realize that the code is working fine. :)

DefaultControls.JPG

Image#1: The default controls when page loads

FirstClick.JPG

Image#2: After clicking "Add More" button

SecondClick.JPG

Image#3: Let's click once more

Yeah, it's working!!!

Conclusion

This article does not tell you to stop using ViewState, but we should use ViewState when required, and in the case of dynamic controls we can avoid ViewState and still get the state in between postback.

History

  • 22nd April, 2009: Initial post

License

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