DrawToBitmap - System.ArgumentException: Parameter is not valid

Viewed 11978

Im creating a Label and sometimes Im using .DrawToBitmap(). I dont know why, but after Im running my program for a while (and calling .DrawToBitmap() often) I get the exception:

System.ArgumentException: Parameter is not valid.
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)

Somehow I cannot call this function that often. If I would radically try this:

while(true)
{

  System.Windows.Forms.Label label = new Label();

  label.Font = new Font("Arial", 20);
  label.Text = "test";

  try
  {
    Bitmap image = new Bitmap(300, 500);
    label.DrawToBitmap(image, label.ClientRectangle);
  }
  catch (Exception e)
  {
    Console.WriteLine(e);
  }
}

I got after 5-6 secs (1000-2000 calls) the exception. What is the problem? How to avoid this?

Edit: Thank you guys for the idea with Dispose() - somehow everything is working perfect if I use it on label. Even if I dont use it on Bitmap its fine. Both of the answers are great, I can only accept 1 of them :(

2 Answers
Related