Web Forms pages, like other Web files processed on the server, make a round trip to the server each time processing is required. Ordinarily, this would mean that all information associated with the form would be lost each time.
However, the Web Forms framework can save the state of the page and its controls. The framework provides these options:
This means that for most ordinary form processing, you do not need to worry about saving and restoring values with each round trip. It also means that if you have some application-specific values that you want to preserve (values not associated with controls), you can do so by taking advantage of the page's automatic facilities.
The state bag is a data structure maintained by the page for retaining values between round trips to the server. By storing a value in the page's state bag, you automatically preserve it between round trips.
The following example illustrates how you might maintain the state of an application value. The code defines a public member called UserType, which stores a numeric value indicating what type of customer is using the form. The UserType member includes get and set functions, so it can be used like a property. Each time the value of the member is changed, its value is stored in the page's state bag. When the value of the member is read, the member's get function extracts the value from the state bag. Because the state bag is saved automatically as part of form processing, the state of this member is preserved between round trips.
[C#]
public int UserType
{
get{
if (State["UserType"] != null)
return (int)State["UserType"];
return 0;
}
set{
State["UserType"] = value;
}
}