SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

Custom Web Part Building: State Management Tips and Tricks

When building custom web parts its essential to understand when controls will contain thier values and when they don't and how to keep variables that will contain their values throughout the web part life cycle.  Especially if you would like to dynamically load one control based on another controls input.

 1. In CreateChildControls, No control will contain a value, not even hidden fields.  This eliminates some uses of a common practice of utilizing hidden field to maintain viewstate.

 2. ViewState Parameters are great for maintaining values throughout the web part lifecycle.  Initialize them in the constructor of a web part to avoid null errors.
Initializing a view state parameter:
  ViewState["parameter1"] = "";
Retrieving a value from view state:
  string this = ViewState["parameter1"].toString();

 3. If you would like to maintain a web parts state while navigation persists in your website, you can utilize session state variables with the following code:
Adding a variable to session state:
  HttpContext.Current.Session.Add("variablename1", "value1");
Retrieving a variable from session state:
  writer.Write("'" + HttpContext.Current.Session["variablename1"] + "'");


Posted 10-10-2007 11:23 AM by ChadClarke

Comments

Links (10/11/2007) « Steve Pietrek’s SharePoint Stuff wrote Links (10/11/2007) « Steve Pietrek’s SharePoint Stuff
on 10-11-2007 7:37 PM

Pingback from  Links (10/11/2007) « Steve Pietrek’s SharePoint Stuff

Jason wrote re: Custom Web Part Building: State Management Tips and Tricks
on 05-30-2008 3:52 PM

w00t!  Thanks!  This is exactly what I was looking for.  The problem with .NET is there is just so much in there, that sometimes it's hard to find exactly what you want.

Abdurrahman's Blog wrote Visual Studio Spoiled Me, and Web Parts Framework Made Me Learn
on 07-27-2008 2:45 AM

It took me sometime until I figured out some facts about Web Parts lifecycle. The following are some

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.