Creating Cookie and Using Cookie

Posted by Johnbhatt under ASP.NET category on | Points: 40 | Views : 1579

Code to Create a Cookie:

protected void Page_Load(object sender, EventArgs e)

int x; // Made a Variable with Datatype Int for Future Use
HttpCookie myCookie; // Defined a Cookie named myCookie.
protected void Button1_Click(object sender, EventArgs e)
x = Convert.ToInt32(TextBox1.Text); // Converted textbox Value which we earlier Did.
myCookie = new HttpCookie("txtValue"); // Assigned Variable myCookie.
myCookie.Value = Convert.ToString(x); // Value assigned to myCookie.
Response.Cookies.Add(myCookie); //This Simple Made a Cookie that will Expire in Session End.
myCookie.Expires = DateTime.Now.AddMinutes(15); // We made is Persistent and stored it for Next 15 minutes.


Code to Access Cookie in anywhere in Application.

protected void Button2_Click(object sender, EventArgs e)

HttpCookie storedCook = Request.Cookies["txtValue"]; // Requested from Server for Cookie
if (storedCook != null)
x = Convert.ToInt32(storedCook.Value); // Converted to Integer again.
TextBox1.Text = Convert.ToString(x * x); // Now Printed Value in Textbox.

Comments or Responses

Login to post response