lenden
lenden

Reputation: 830

PictureBox always throws NullReferenceException

A simple code that should show an image using PictureBox doesn't work (frm is my form):

PictureBox pb = new PictureBox();
pb.Image = new Bitmap("1.jpg");
pb.SizeMode = PictureBoxSizeMode.Zoom;
frm.Controls.Add(pb);

When event with this code happens I have NullReferenceExcpetion

The error occurs at frm.Controls.Add(pb)

The exception is:

System.NullReferenceException: Object reference not set to an instance of an object. at Form1.HotKeyManager_HotKeyPressed(Object sender, HotKeyEventArgs e) in C:\Users\Алексей\Documents\Visual Studio 2010\Projects\NotepadCSharpSetup\WinFormsAgain\RealTrayForm\Test.cs:line 52

Full code :

static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
    Size ScreenSize = Screen.PrimaryScreen.Bounds.Size;

    Bitmap image = new Bitmap(ScreenSize.Width, ScreenSize.Height);
    using (Graphics g = Graphics.FromImage(image))
    {
        g.CopyFromScreen(Point.Empty, Point.Empty, ScreenSize);
    }
    Bitmap preview = new Bitmap(image.Width / 10, image.Height / 10);
    using (Graphics gr = Graphics.FromImage(preview))
    {
        gr.SmoothingMode = SmoothingMode.AntiAlias;
        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
        gr.DrawImage(image, new Rectangle(0, 0, image.Width / 10, image.Height / 10));
    }
    preview.Save("1.jpg");

    Form frm = (Form)sender;
    PictureBox pb = new PictureBox();
    pb.Image = new Bitmap("1.jpg");
    pb.SizeMode = PictureBoxSizeMode.Zoom;
    frm.Controls.Add(pb);

}

Upvotes: 1

Views: 2344

Answers (3)

Tom
Tom

Reputation: 2390

This line:

Form frm = (Form)sender;

Will actually cause an InvalidCastException (or something similar) if the sender is not of Type Form.

The other way of casting objects is:

Form frm = sender as Form;

This will actually set frm to null if sender is not of type Form (instead of throwing the exception).

I would place a break point and check which object is actually null. My guess is that sender is null from the start, and casting it to Form does nothing.

Upvotes: 1

MBen
MBen

Reputation: 3996

I don't believe the new keyword returns Null, unless you have no memory. The bet is that the sender is not the Form

Form frm = (Form)sender;

I think this line is null, that's why frm.Controls.Add(pb) fails.

Upvotes: 1

Gaz Winter
Gaz Winter

Reputation: 2989

The most likely cause of this is because the Bitmap doesnt exist at the location that its currently looking.

Make sure you have the correct path to the image that you are trying to display in the picture box.

Upvotes: 0

Related Questions