How can I check if a cookie value has been set in C#?

Posted on 2006-06-02
Last Modified: 2008-02-20
I have a situation where I won't know whether or not a cookie value has been set, and I need a way to check this.

In my code behind (test.aspx.cs) I have the following line

   Label.Text = Request.Cookies["somecookie"].Value;

This will throw a NullReferenceException if "somecookie" was never set, and from that point on, I can't read any other cookie info.

How can I test whether or not this cookie was set before applying the ".Value" to the cookie object?
Question by:cgipisani
    1 Comment
    LVL 17

    Accepted Solution

    if (Request.Cookies["somecookie"] != null)
        Label.Text = Request.Cookies["somecookie"].Value;

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
    ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now