How to use application object in asp.net in real time?

Application object is used to store the values and access variables from any page in application. It is same as session object only the difference is session object is used to maintain the session for particular user. If one user enters in to the application then session id will create for that particular user if he leaves from the application then the session id will deleted.

If they again log in to the web application they will get different session id but application object is same for all users once application object is created that application object is used throughout the application regardless of user. The values stored in application object accessed throughout all the pages in application and we can change the application object in one place those changes automatically reflected in all the pages.

You can create application objects in Global.asax file and access those variables throughout the application. To know about how to add Global.asax file check the post here:

Right click on project -> Add New Item -> Select Global Application class. (Note: you can have only one global.asax file per project)

Add following code in Global.asax file like this:


void Application_Start(object sender, EventArgs e)
{
     // Code that runs on application startup
     Application["UserID"] = "Kunal";
}

 After this to display application object value on aspx page write the following code:

<html> 
<head> 
<title>Application Object Sample</title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<asp:Label id="lblText" runat="server"></asp:Label> 
</form> 
</body> 
</html>

 After that write the following code in code behind:

public void Page_Load(object sender, EventArgs e)
{
    this.lblText.Text =  "User Name: " + Application["UserID"] + "<br>";
}

And now run the application you will see the application object value in your page.

application object,application object in asp.net, state management, an example

 
Top