1

I have image slider, and in IE I have an error.

This is my code:

*//Složka s obrázky partnerů
string slozka = HttpContext.Current.Server.MapPath("~/Partneri");

protected void Page_Load(object sender, EventArgs e)
{
    int cislo_obrazku = 0;
    if (!Page.IsPostBack)
    {
        ArrayList slide = new ArrayList();
        System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(slozka);
        foreach (FileInfo eachfile in inputDir.GetFiles())
        {
            slide.Add(eachfile.ToString());
            cislo_obrazku += 1;
        }
        Session["cislo_obrazku"] = cislo_obrazku;
        Session["obrazky"] = slide;
        Casovac(this, new EventArgs());
    }
}

protected void Casovac(object sender, EventArgs e)
{
    ArrayList slide = new ArrayList();
    slide = (ArrayList)Session["obrazky"];
    if ((Session["aktualni"] != null) && (Convert.ToInt32(Session["aktualni"]) != Convert.ToInt32(Session["cislo_obrazku"]) - 1))
    {
        //Posun na další
        Image1.ImageUrl = "~\\Partneri\\" + slide[Convert.ToInt32(Session["aktualni"]) + 1].ToString();
        Session["aktualni"] = Convert.ToInt32(Session["aktualni"]) + 1;
    }
    else if (Session["aktualni"] == Session["cislo_obrazku"])
    {
        //Pokud není další, začni znovu
        Image1.ImageUrl = "~\\Partneri\\" + slide[0].ToString();
        Session["aktualni"] = 0;
    }
    else
    {
        if (Convert.ToInt32(Session["cislo_obrazku"]) != 0)
        {
            //Initally load the first image in the image control
            Image1.ImageUrl = "~\\Partneri\\" + slide[0].ToString();
            Session["aktualni"] = 0;
        }
    }
}

Error: NullReferenceException was unhandled by user code

Error point to this:

Image1.ImageUrl = "~\\Partneri\\" + slide[0].ToString();  

and

Image1.ImageUrl = "~\\Partneri\\" + slide[0].ToString();

Have you some idea?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
koky
  • 21
  • 1
  • 7

2 Answers2

2

NRE is possibly the easiest exception to understand. It is also one of the most common problems when you have not coded defensively enough.

Quite simply, it means you are trying to access a property/method on an object which is null.

In your case

 slide[0].ToString();

either

  • slide is null
  • slide[0] is null.

Set a breakpoint, debug your app. Determine Which is null, and either account for that (eg, with a default) or throw a more meaningful exception if it truly is an exceptional circumstance for that object to be null.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

The session object obrazky has not been initialized.

Add a null check after:

slide = (ArrayList)Session["obrazky"];
jgauffin
  • 99,844
  • 45
  • 235
  • 372