Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Maintain Control State in ASP.NET 2.0

Maintain Control State in ASP.NET 2.0


This article describes a simple approach to maintaining control state in an ASP.NET 2.0 custom web control. Control state is a new construct within ASP.NET 2.0 and it is really nothing more than view state however it is view state with a significant advantage; that advantage is that other developers using your control cannot disable control state as they can view state.

Author Rank:
Total page views :  30230
Total downloads :  231
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ControlStateExample.zip
 
Become a Sponsor

Introduction:

This article describes a simple approach to maintaining control state in an ASP.NET 2.0 custom web control.  Control state is a new construct within ASP.NET 2.0 and it is really nothing more than view state however it is view state with a significant advantage; that advantage is that other developers using your control cannot disable control state as they can view state. 

Control state survives even if the developer using the custom control disables view state.  The advantage is pretty obvious; in prior versions of Visual Studio, the consumer of a custom control could disable view state; if the control relied on view state to maintain state information, the control would cease to function or at least misbehave.  Creating control state removed the ability of a control consumer to disable view state based state management within the control; naturally the control designer may still opt to not use either view state or control state based state management.

One final note, most of the examples I have personally viewed regarding control state show a mechanization in which only one value is stored in the control state; the accompanying example herein shows how store a greater number of values of different data types can be easily stored in the control state.

Getting Started:

In order to get started, open up the Visual Studio 2005 IDE and start a new project.  From the new project dialog (Figure 1), under project types, select the "Windows" node from beneath "Visual Basic", then select the "Web Control Library" template in the right hand pane.  Key in a name for the project and then click "OK".

Once the project has opened; right click on the solution and click on the "Add" menu option, and then select "New Item".  When the "Add New Item" dialog appears (Figure 2), select the "Web Custom Control" template, after selecting the template, key "ExampleStateControl.vb" into the name field and then click "Add" to close the dialog.  You may now delete the default web control that was created  when the project was originally initialized from the template.

At this point, we should have an open web control library project with a single web control named "ExampleStateControl.vb" in that project. 

One last step prior to writing the code for this project will be to validate the references and import statements.  Compare your import statements with this list and make any adjustments necessary:

Imports System

Imports System.ComponentModel

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Figure 1:  Visual Studio 2005 New Project Dialog

Figure 2:  Add New Item Dialog

We are now ready to add the code necessary to make this control functional.  At this point, the project's code should look something like this:

Imports System

Imports System.ComponentModel

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

 

<Serializable()>_

<ToolboxData("<{0}:ExampleStateControl runat=server></{0}:ExampleStateControl>")>_

Public Class ExampleStateControl

Inherits WebControl

If we are in sync here, we can now start to write the necessary code.  To begin, create a declarations region and add the following code to  that region:

#Region "Declarations"

 

    Private mCurrentProps As New CurrentProperties

 

    <Serializable()> _

    Private Structure CurrentProperties

        Dim pFirstName As String

        Dim pLastName As String

        Dim pAge As Integer

        Dim pCity As String

        Dim pState As String

        Dim pCountry As String

        Dim pCitizen As Boolean

    End Structure

 

#End Region

In examing the declarations, note that there is a structure called CurrentProperties defined and there is a private member variable declared (mCurrentProps) that is of the CurrentProperties structure type.  This instance of the structure is what we will be putting into and collecting out of control state.

The next thing to do will be to add the properties necessary to support the example custom web control.  There is one property for each element contained in the structure.  To accomplish this task, create a properties region and add in the following code:

#Region "Properties"

 

    <Browsable(True)>_

    <Category("Name")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property FirstName() As String

        Get

            Return mCurrentProps.pFirstName

        End Get

        Set(ByVal value As String)

            mCurrentProps.pFirstName = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Name")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property LastName() As String

        Get

            Return mCurrentProps.pLastName

        End Get

        Set(ByVal value As String)

            mCurrentProps.pLastName = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Status")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property Age() As Integer

        Get

            Return mCurrentProps.pAge

        End Get

        Set(ByVal value As Integer)

            mCurrentProps.pAge = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Status")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property IsCitizen() As Boolean

        Get

            Return mCurrentProps.pCitizen

        End Get

        Set(ByVal value As Boolean)

            mCurrentProps.pCitizen = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Residence")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property City() As String

        Get

            Return mCurrentProps.pCity

        End Get

        Set(ByVal value As String)

            mCurrentProps.pCity = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Residence")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property State() As String

        Get

            Return mCurrentProps.pState

        End Get

        Set(ByVal value As String)

            mCurrentProps.pState = value

            SaveControlState()

        End Set

    End Property

 

    <Browsable(True)>_

    <Category("Residence")>_

    <DefaultValue("")>_

    <Localizable(True)>_

    <NotifyParentProperty(True)>_

    Public Property Country() As String

        Get

            Return mCurrentProps.pCountry

        End Get

        Set(ByVal value As String)

            mCurrentProps.pCountry = value

            SaveControlState()

        End Set

    End Property 

#End Region

Note that each property's get and set methods either updates or retrieves from the active instance of the "ControlProps" structure.  No other private member variables are used to retain each of the property's current values.

The next step in the process is to add in the methods used by the control.  Add a Methods region to the code page and key in the following methods:

#Region "Methods"

 

     Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

        Page.RegisterRequiresControlState(Me)

        MyBase.OnInit(e)

    End Sub

 

     Protected Overrides Function SaveControlState() As Object

        Return Me.mCurrentProps

    End Function

 

     Protected Overrides Sub LoadControlState(ByVal savedState As Object)

        mCurrentProps = New CurrentProperties

        mCurrentProps = CType(savedState, CurrentProperties)

    End Sub 

#End Region

Notice that in the init, the first line is used to instruct the page to maintain control state.  The next two methods are used to save the current control state or to reload the control states values from the saved control state.

At this point, the only thing left to do is to define how the control will be rendered.  To complete this step, create a "Rendering" region and, within this region, override the RenderContents sub with the following code:

#Region "Rendering"

 

    Protected Overrides Sub RenderContents(ByVal writer As

    System.Web.UI.HtmlTextWriter)

 

        Try

            writer.RenderBeginTag(HtmlTextWriterTag.Table)

            writer.Write("<b>Control State Properties</b><hr />")

            '''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("Name: ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pFirstName + " " +

mCurrentProps.pLastName)

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("Age: ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pAge)

            writer.RenderEndTag()

 

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("Is Citizen:     ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pCitizen.ToString())

            writer.RenderEndTag()

 

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("City: ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pCity.ToString())

            writer.RenderEndTag()

 

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("State: ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pState.ToString())

            writer.RenderEndTag()

 

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

            writer.RenderBeginTag(HtmlTextWriterTag.Tr)

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write("Country: ")

            writer.RenderEndTag()

 

            writer.RenderBeginTag(HtmlTextWriterTag.Td)

            writer.Write(mCurrentProps.pCountry.ToString())

            writer.RenderEndTag()

 

            writer.RenderEndTag()

 

            ''''''''''''''''''''''''''''''''''''''''''''

 

            writer.RenderEndTag() ' close the table

 

        Catch ex As Exception

 

            writer.Write(Me.ID)

 

        End Try

 

    End Sub 

#End Region

As you can see, the rendering of this example control is pretty simple; it is just generating a table and displaying each control state maintained property value in separate rows within that table.

The control is now complete.  Prior to testing the control, rebuild the project.  Once that has been completed and any errors encountered are repaired, it is time to test the control.  To test the control, add a new web site project to the web control library project currently open.  Once the test web site has been created, set the test project as the start up project by right clicking on the web site solution in the solution explorer and selecting the "Set as Start Up Project" menu option.  Next, locate the Default.aspx page in the web site solution, right click on this page and select the "Set as Start Page" menu option.

If you downloaded the sample project, you may prefer to open IIS and create a virtual directory pointing to the web site and then open the project from within Visual Studio 2005.  The solution contains both the sample web site and the sample custom web control library project.

Open the Default.aspx page for editing.  Locate the newly created control in the toolbox (it should be at the top) and, if you are not working with the sample web site, drag the "ExampleStateControl" control onto the page (Figure 3).

Figure 3:  Custom Control in the Toolbox

If you are working with the sample code, you may still click on the control and set its properties through the property grid within the Visual Studio 2005 IDE if you wish to do so.

Build the application and run it; you should now be looking at the site displayed in the following figure  (Figure 4).  With the page running, you may key in new values into the spaces provided in the lower half of the page and hit the enter key or click on the submit button to force a post back.  In either case, the application will update the current properties and save the control state; after the post back has finished you will note that the values stored in the control state have been used in the rendering of the control.

Figure 4:  Control state managed control in operation


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Controlstate is kept anyway !!!? by jo On December 2, 2006

HI!

 

If I comment the :

Protected Overrides Function SaveControlState() As Object

Return Me.mCurrentProps

End Function

 

it still keeps the values. Viewstate is also turned off.

How does it keep the values?

 

Kind regards

 

Legends

 

 

Reply | Email | Delete | Modify | 
How to maintain the state of a page after clicking on Refresh(Post Back) by vivek On September 6, 2007
Hi scott, i have got a problem here. In my form i have couple of text fields and a submit button. After submitting my form when i click on Refresh the same data gets inserted again.This happens as many times i click on refresh. What i would ideally like is to insert the data only once even after pressing on refresh button and the data should only be inserted when i click on submit button. Plz lemme know if there's any solution to this problem. I work on Asp DotNet 2.0.
Reply | Email | Delete | Modify | 
Re: How to maintain the state of a page after clicking on Refresh(Post Back) by Scott On September 6, 2007

That is the intent of LoadControlState; you may want to conditionally load control state rather than load it each time.  There is a so-so example of this located here:

http://msdn2.microsoft.com/en-us/library/system.web.ui.control.loadcontrolstate.aspx

If you don't want to persist the control state across postbacks then you might want to dispense with the use of control state (and view state) in your specific application; or, if using control state, restrict it to only those items that you want to survive a postback.

Reply | Email | Delete | Modify | 
state maintained any way by hassan On April 27, 2009
i commented out savecontrolstate () in some properties eg city but still view state is maintained even if i set the controls enableviewstate to false. i change city and when i post back state is maintained no matter how many times i do submit page
Reply | Email | Delete | Modify | 
Re: state maintained any way by Scott On April 27, 2009
The article is about maintaining control state regardless of view state and as a function of custom control development.  If you don't want to maintain control state, just don't implement it.  Comment out the entire methods region of the code.
Reply | Email | Delete | Modify | 
as by watches On July 11, 2010
n general Hogan are made from very flexible materials and have a rubber sole. When they first entered the market Hogan scarpe donna were quite simple but the growing popularity has increased competition and spurned a number of new designs. While other styles of hogan donna such as casual loafers or dress shoes tend to come in one generic mould, Hogan uomo are designed to support and contrast an athlete s foot.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.