Referencing Dynamic PictureBox

mjohnson3091

Freshman
Joined
Aug 10, 2004
Messages
31
Location
Lancashire, UK
As my dynamic form creation playing is getting further I seem to be getting more problems. I'm creating a form based upon a received XML message, which may or maynot contain a call to create a new PictureBox.

If it does, I create the picturebox and all that works fine.

The problem I have is, if I assign an event to a button, for example to save the image from the PictureBox, the code won't compile, because it tells me that the reference to the picturebox doesn't exist, which I suppose is true as it hasn't been created yet. How can I get around this?

Example of my code...

Code:
// This is called if we need to add a new picturebox
void AddPicture()
{

  PictureBox img1 = new PictureBox();
  img1.Width=200;
  img1.Height=200;
  img1.Left=50;
  img1.Top=50;
  img1.BackColor=Color.White;
  this.Controls.Add(img1);
  img1.Visible=true;

}


// This is called to attempt to save the image
void SavePicture()
{
   ((PictureBox) img1).Image.Save("C:\\temp\\pic.bmp");
}

I can understand why it fails, because at design time img1 doesn't exist, I just don't know how to solve it or get around it.

Any help appreciated.

Thanks in advance.
 
You could declare img outside of the AddPicture method and then the variable would be accessible from the SavePicture method, you would need to check for null before using it though.
 
PlausiblyDamp said:
You could declare img outside of the AddPicture method and then the variable would be accessible from the SavePicture method, you would need to check for null before using it though.


Works a treat, thanks again for your help mate.
 
Back
Top