Click here to Skip to main content
Click here to Skip to main content

ViewState in Dynamic Control

, 22 Apr 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

<%@ 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.

/// <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:

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.

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. Smile | :)

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)

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)

Comments and Discussions

 
GeneralGood Job Pinmember King_Fisher23-Apr-14 0:36 
GeneralHow to Insert these value into sql. PinmemberMember 1071443731-Mar-14 21:55 
QuestionAdding the values to a database PinmemberMember 106023595-Mar-14 4:40 
QuestionSuper Work PinmemberIhtesham12-Jun-12 3:04 
GeneralMy vote of 5 PinmemberWeerayut Teja14-Nov-11 23:14 
Oh Excellent article, I'm finding solution. and this article have been answer it.
Generalnice work Pinmemberbluevoodoo14-Jun-10 13:45 
GeneralA Tip While Using ViewState Pingroupelizas16-Feb-10 21:10 
GeneralValues of ContactDetails PinmemberNZibir11-Oct-09 3:25 
GeneralLImited value Pinmembergstolarov27-Apr-09 20:09 
GeneralSlightly messy and not scalable Pinmemberyafi27-Apr-09 2:44 
JokeRe: Slightly messy and not scalable PinmemberStranger_than_Fiction27-Apr-09 22:26 
GeneralRe: Slightly messy and not scalable Pinmemberyafi27-Apr-09 22:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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