0

Different issue to Dictionary in C# WinForms App causing null reference

I'm using Visual Studio 2013 to create a Visual C# Windows Forms Application and I'm not using the Designer to setup the form.

I'm trying to use a Dictionary to store Bitmaps so that I can call them later by name. But when I debug the script I get the error:

An unhandled exception of type 'System.NullReferenceException' occurred in SimpleForm.exe
Additional information: Object reference not set to an instance of an object.

From the line:

dirStrBmp.Add("TempImageName", bmpTemp);

Any help would be greatly appreciated.

Cut down version of code which still produces the error:

using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace SimpleForm
{

    public class Test : Form
    {

        static Bitmap bmpTemp;
        private Dictionary<string, Bitmap> dirStrBmp;

        public Test()
        {
            bmpTemp = new Bitmap("graphic.png");
            dirStrBmp.Add("TempImageName", bmpTemp);
        }

    }

}
Community
  • 1
  • 1
RebDev
  • 335
  • 1
  • 5
  • 13

1 Answers1

4

Modify the declaration of your dictionary like this:

 private Dictionary<string, Bitmap> dirStrBmp = new Dictionary<string,Bitmap>();
King King
  • 61,710
  • 16
  • 105
  • 130