Billy Brown
Billy Brown

Reputation: 23

ASP.NET/VB Reading/Writing Cookies - Object not set to instance of an object

so I have this code:

        Try
        If Request.Cookies("curUsrId")("id") Is Nothing Then
            Dim cke As HttpCookie = New HttpCookie("curUsrId")
            cke("id") = CStr(myUser.Id)
            cke.Expires = Now.AddDays(35)
            Response.Cookies.Add(cke)
        Else
            If Request.Cookies("curUsrId")("id") = "2" Then
                grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
                chkPaging.Checked = True
            Else
                grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
                chkPaging.Checked = False
            End If
        End If
    Catch ex As Exception
        lblErrorMsg.Visible = True
        txtErrorTxt.Visible = True
        txtErrorTxt.Text = ex.Message
    End Try

I'm trying to read/write to a cookie, but everytime I run this, I get a "Object not set to an instance of an object" error.

Does anyone know why?


I changed the code slighty, still the same error? Per the comment below, I do check to see if the value is nothing.

            Try
            If Request.Cookies("curUsrId").Value Is Nothing Then
                Dim cke As HttpCookie = New HttpCookie("curUsrId")
                cke.Value = CStr(myUser.Id)
                cke.Expires = Now.AddDays(35)
                Response.Cookies.Add(cke)
            Else
                If Request.Cookies("curUsrId").Value = "2" Then
                    grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
                    chkPaging.Checked = True
                Else
                    grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
                    chkPaging.Checked = False
                End If
            End If
        Catch ex As Exception
            lblErrorMsg.Visible = True
            txtErrorTxt.Visible = True
            txtErrorTxt.Text = ex.Message
        End Try

ANOTHER EDIT:

I added a breakpoint at the Try line, guess, what it doesn't hit. "No symbol information loaded etc". I tried loading the DLL manually, I've rebuilt the solution etc, no difference?

Upvotes: 2

Views: 9130

Answers (1)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You are getting this exception because you are trying to read value of a cookie which does not exist in cookies collection.

If Request.Cookies("curUsrId").Value //Here you are trying to read value from cookie wich is not set yet

Try this for C#

if(Request.Cookies.Get("curUsrId")==null)
{
//Your code to add cookie
}

In VB.Net

If Request.Cookies.Get("curUserId") Is Nothing Then

Upvotes: 5

Related Questions