Parameter is invalid, when I replace a bmp into PictureBox

88 Views Asked by At

I want to replace PictureBox.Image with a new bmp.Like these:

Bitmap bmp = new Bitmap(100, 100);
Graphics g1 = Graphics.FromImage(bmp); 
g1.FillRectangle(Brushes.Red, new Rectangle(0, 0, 100, 100));
PbDm3.Image = bmp;
if(bmp != null)
{
    bmp.Dispose();
}

But it will tell me Parameter is invaild.

Tips: I tried add Garbage collection by myselef, it's not useful.

I want to know why is it happened, and how to fix it.

1

There are 1 best solutions below

1
Mahdi Jamal On

Remove this code because when you dispose the bmp, the picture will be lost

if(bmp != null)
{
    bmp.Dispose();
}

After use Graphics class, Dispose this

Graphics g1 = Graphics.FromImage(bmp); 
g1.FillRectangle(Brushes.Red, new Rectangle(0, 0, 100, 100));
g1.Dispose();

Or

using (Graphics g1 = Graphics.FromImage(bmp))
{
    g1.FillRectangle(Brushes.Red, new Rectangle(0, 0, 100, 100));
}