Application state is a data repository used to store data on the application machine. The data is stored in the memory and can be easily retrieved. It acts as a global variable shared by multiple users or sessions. A small portion of often used data can be stored in the application state.
The Instance, HttpApplicationState will be created only once upon initial user request. After initial user request, it can be accessed using the Application property of the HttpContext
The following example will show how to implement the Application State to increment the values.
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Application State</title>
- <form id="form1" runat="server">
- <h3>Application State Example</h3>
- <asp:Label ID="lblCounter" runat="server" Text=""></asp:Label>
- <br />
- <asp:Button ID="btnCount" runat="server" Text="Count"
- onclick="btnCount_Click" />
- protectedvoid btnCount_Click(object sender, EventArgs e)
- int MyCount = 0;
- if (Application["Counter"] != null)
- MyCount = (int)Application["Counter"];
- Application["Counter"] = MyCount;
- lblCounter.Text = MyCount.ToString();
In the above example Application variable is used in the application. Application variable can be initialized in the Global.asax file also. There are specific methods to initialize the Application State variables. In the application folder you can get the Global.asax file. This file will be parsed and compiled dynamically. You cannot make any direct URL request during the runtime. When the application starts to run, then the Application_Start event will be started automatically. Below is the example to implement the Application state variable in the Application_Start Event.
- void Application_Start(object sender, EventArgs e)
- Application["UserName"] = " TestUser";
When the application starts the UserName will be stored in the application state. This value will be available to the all users. The following code will get the value from the application state and displays in the label.
- lblUserName.Text = Application["UserName"].ToString();