Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET

ViewState in Dynamic Control

Rate me:
Please Sign up or sign in to vote.
4.81/5 (15 votes)
22 Apr 2009CPOL2 min read 109.7K   3.1K   28   15
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)


Written By
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

 
Questionsaving dynamic content to sql database Pin
Member 1190160616-Aug-15 1:55
Member 1190160616-Aug-15 1:55 
QuestionAdd data into database Pin
Amira El-Baroudy3-Aug-15 23:58
Amira El-Baroudy3-Aug-15 23:58 
QuestionExcellent Pin
Jitendra200520-Mar-15 19:24
Jitendra200520-Mar-15 19:24 
GeneralGood Job Pin
King Fisher22-Apr-14 23:36
professionalKing Fisher22-Apr-14 23:36 
GeneralHow to Insert these value into sql. Pin
Member 1071443731-Mar-14 20:55
Member 1071443731-Mar-14 20:55 
QuestionAdding the values to a database Pin
Member 106023595-Mar-14 3:40
Member 106023595-Mar-14 3:40 
QuestionSuper Work Pin
Ihtesham12-Jun-12 2:04
Ihtesham12-Jun-12 2:04 
GeneralMy vote of 5 Pin
Weerayut Teja14-Nov-11 22:14
Weerayut Teja14-Nov-11 22:14 
Generalnice work Pin
bluevoodoo14-Jun-10 12:45
bluevoodoo14-Jun-10 12:45 
GeneralA Tip While Using ViewState Pin
elizas16-Feb-10 20:10
elizas16-Feb-10 20:10 
I am sharing a tip with you all regarding viewstate.Hope it would be useful.


View state maintains data in a page across postbacks. And this data passes in form of hidden field data. There is a certain limitation of this hidden field. If your hidden field will be greater than that specified value, then sometimes firewalls and proxy servers refuse to let your data passes through. And in that case you have to disable your view state .This might cause many problem if you want your data to be passed.

So to overcome this problem you can do viewstate chunking. This is a process of splitting the data into multiple chunks and putting them into multiple hidden fields, So that there will not be any problem to your data to pass through. This chunking is done by adding "MaxPageStateFieldLength" property in the page tag in web.config file. The default value is -1 which indicates there is no maximum limit of data. You have to give the integer value which indicates the maximum bytes size for a viewstate field.

For more details log on to:
http://www.mindfiresolutions.com/A-Tip-While-Using-ViewState-548.php
Cheers,
Eliza

GeneralValues of ContactDetails Pin
NZibir11-Oct-09 2:25
NZibir11-Oct-09 2:25 
GeneralLImited value Pin
gstolarov27-Apr-09 19:09
gstolarov27-Apr-09 19:09 
GeneralSlightly messy and not scalable Pin
yafi27-Apr-09 1:44
yafi27-Apr-09 1:44 
JokeRe: Slightly messy and not scalable Pin
Stranger_than_Fiction27-Apr-09 21:26
Stranger_than_Fiction27-Apr-09 21:26 
GeneralRe: Slightly messy and not scalable Pin
yafi27-Apr-09 21:54
yafi27-Apr-09 21:54 

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

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