How to use Context Object in ASP.Net C#

The ASP.Net Context object is the same as the Session Object as we learnt previous asp.net post.

The Context Object is used to store the Value and Send it to the other page in ASP.Net.

The main Difference between Context and Session is the Context Object will be null when we send page to server.
That means we we use Context Object we must use Server.Transfer Method to redirect user to other page.

If we use Response.Redirect the Context value will be null on other page.

we can use Response.Redirect and Server.Transfer with Session Object in ASP.Net, but Response.Redirect cant use with Context Object in ASP.Net.

 

The Syntax of Context Object in ASP.Net

Declare the Context Object in ASP.Net

Context.Items[“Id”]=value;
Server.Transfer(“NextPage.aspx”);

 

Retrieve the Context Value on NextPage in ASP.Net

string myvalue = Context.Items[“Id”].ToString();
Response.Write(“Your Value = “+ myvalue);

 

learn more about Response.Redirect() and Server.Transfer() in ASP.Net
What is Session() in ASP.Net

 

Here we tack an Example of Context Object in ASP.Net.

First Create a ASP.Net website and create two web form and Design the web form like:

How to use Context Object in ASP.Net C#
How to use Context Object in ASP.Net C#

Write the Below code on SEND Button click event in ASP.Net

protected void Button1_Click(object sender, EventArgs e)
{
Context.Items[“txt”] = TextBox1.Text;
Server.Transfer(“answer.aspx”);
}

 

How to use Context Object in ASP.Net C#
How to use Context Object in ASP.Net C#

Write below code on Page_Load Event of other page where we want display a value of Context object.

protected void Page_Load(object sender, EventArgs e)
{
Label2.Text = Context.Items[“txt”].ToString();
}

 

How to use Context Object in ASP.Net C#
How to use Context Object in ASP.Net C#

learn about asp.net session timeout ?

I hope this asp.net Example of Context object will help you……

Leave a Reply

Your email address will not be published. Required fields are marked *