This documentation is archived and is not being maintained.

StateBag.Add Method

Adds a new StateItem object to the StateBag object. If the item already exists in the StateBag object, this method updates the value of the item.

Namespace: System.Web.UI
Assembly: System.Web (in system.web.dll)

public StateItem Add (
	string key,
	Object value
public StateItem Add (
	String key, 
	Object value
public function Add (
	key : String, 
	value : Object
) : StateItem
Not applicable.



The attribute name for the StateItem.


The value of the item to add to the StateBag.

Return Value

Returns a StateItem that represents the object added to view state.

Exception typeCondition


key is a null reference (Nothing in Visual Basic).

- or -

The number of characters in key is 0.

The following code example demonstrates using the Add method.

void MovePiece(string fromPosition, string toPosition) {
   StateBag bag = ViewState;
   object piece = bag[fromPosition];
   if (piece != null) {
      bag.Add(toPosition, piece);
   else {
      throw new InvalidPositionException("There is no game piece at the \"from\" position."); 

Windows 98, Windows Server 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0