0

I'm Writing a Code with ASP.Net to make a Shopping WebSite

and This Error appear :

Object reference not set to an instance of an object.

at this Line of Code :

 tot = tot +(Convert.ToInt32(a[2].ToString())+Convert.ToInt32(a[3].ToString()));  

the Full Code is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class user_user : System.Web.UI.MasterPage
{
    string s;
    string t;
    string[] a = new string[6];

    int tot = 0;
    int totcount = 0;

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Cookies != null)
    {
        s = Convert.ToString(Request.Cookies["aa"].Value);
        string[] strarr = s.Split('|');

        for (int i = 0; i < strarr.Length; i++)
        {
            t = Convert.ToString(strarr[i].ToString());
            string[] strarr1 = t.Split(',');
            for (int j = 0; j < strarr1.Length; j++)
            {
                a[j] = strarr1[j].ToString();

            }

            tot = tot + (Convert.ToInt32(a[2].ToString()) + Convert.ToInt32(a[3].ToString()));
            totcount = totcount + 1;

            carttotitem.Text = totcount.ToString();
            carttotprice.Text = tot.ToString();
        }
    }

}

}

so What Should I do to Solve This Error

Please Help Me

  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Rui Jarimba Jul 22 '18 at 11:58
  • 1
    There's no point calling `ToString()` on strings, and even less point calling `Convert.ToString()` on them. The issue you're having though, is that the format of that cookie is not as you're assuming it will be. Fix the cookie, and/or code to validate the format, handling the case when it's not as expected in a way that suits your app; e.g. perhaps return a 4xx error. Currently you're assuming each |-separated segment has at least 4 components, separated by commas, the 3rd and 4th of which are numbers. Clearly this isn't the case. – sellotape Jul 22 '18 at 12:41

2 Answers2

0

Try to include the ? before the ToString. It will be like this:

a[2]?.ToString ()

phduarte
  • 365
  • 2
  • 9
  • this error appear : Error CS8026 Feature 'null propagating operator' is not available in C# 5. Please use language version 6 or greater. – zainab mostafa Jul 22 '18 at 12:08
  • Then so, try the old way, including a if statement before the calculation, testing the if(a[2] != null). The Null operator just work with the new versions of C#. – phduarte Jul 22 '18 at 12:16
0

Try to append your array declaration string[] a = new string[6]; inside page_load event handler method body because its at master page class scope and its getting lost when the page gets requested.

Voice Of The Rain
  • 495
  • 1
  • 8
  • 24