Singleton class for public variables not assigning value to Bitmap (pictureBox.Image)

Hi,

So I have a pictureBox on a form and need to write pixels to it. I have a couple of methods to do this, and dont want to be passing the variable containing the Bitmap that gets assigned to it to all those methods.

Im using a singleton class holding a few variables that will remain constant and are declared at the loading of the form (canvasWidth and height etc.) to access public variables and this is working for all the variables, except for the Bitmap, which just stays null, even after writing the new image to it.

My Form Load code is:

public Form1() { InitializeComponent(); Globals Globals = new Globals(); int zoom = 1; zoom = trackBar1.Value; label2.Text = ("Zoom level: " + Convert.ToString(zoom)); Globals.bmp = (Bitmap)pictureBox1.Image; Globals.canvasWidth = 100; Globals.canvasHeight = 700; } 

And my singleton Globals class is:

public class Globals { private static Bitmap v_bmp; public static Bitmap bmp { get { return v_bmp; } set { v_bmp = value; } } private static int v_canvasWidth; public static int canvasWidth { get { return v_canvasWidth; } set { v_canvasWidth = value; } } private static int v_canvasHeight; public static int canvasHeight { get { return v_canvasHeight; } set { v_canvasHeight = value; } } public Globals() { canvasWidth = 10; canvasHeight = 230; } } 

Globals.canvasWidth and Globals.canvasHeight both recieve the new values of 100 and 700 correctly, but Globals.bmp is remaining null when the prgram is run.

The program crashes with a null reference exception at the following line:

private int pixel(int xpos, int ypos, Color c) { if(xpos< 0) { xpos = 0; } if (ypos < 0) { ypos = 0; } Globals.bmp.SetPixel(xpos, ypos, Color.FromArgb(255, c.R, c.G, c.B)); // crashes here pictureBox1.Image = (Bitmap)bmp; return 1; } 

Can anyone suggest a reason for this, or a way to fix it? Thanks,

by tburn1 via /r/csharp

Leave a Reply