Today’s post is about how we can use Cookie to store data temporarily. While working on one project for frontend application my client told me that they need some sort of functionality so that user somehow can temporarily store some of the form data and can use the same data when they run the application again. And without any hesitation the first thought came in my mind was to use cookie for this purpose.

I have written a simple code to demonstrate the use of HTTPCOOKIE to create cookie and then use the cookie to retrieve information from it. It is a simple two textbox , buttons and a label form. It accepts name (last and first) from user and sets it into cookie and then retrieves it from cookie in event of button click (if present, else it displays message that it has not found any cookie !!)

The backend code is as follows,

  protected void Button1_Click(object sender, EventArgs e)
            HttpCookie test = new HttpCookie("testC");
            test["Lname"] = TextBox1.Text;
            //test.Values.Add("Lname", TextBox1.Text);
            test["Fname"] = TextBox2.Text;
            //test.Values.Add("Fname", TextBox2.Text);
            test.Expires = DateTime.Now.AddHours(1);
            Label1.Text = "Cookie Created";

        protected void Button2_Click(object sender, EventArgs e)
            if (Request.Cookies["testC"] != null)
                Label1.Text = (Request.Cookies["testC"]["Lname"] + Request.Cookies["testC"]["Fname"]);
                Label1.Text = " No Cookie Found !!!";

And as you can it its nothing fancy about this program, so I don’t think I need to explain anything.

I hope that it may be helpful to someone like me …

That’s it for now …

It’s Just A Thought … fingerscrossed

Gaurang Sign

Random Posts:

Similar Posts: