I have two pictureboxes in two different forms.
I want to transfer the image of firstpicturebox to picturebox1.
So, can anyone help and provide the solution for the same.
You can send it using Form2 Constructor
Try This:
Form1:
Form2 form2 = null;
private void button1_Click(object sender, EventArgs e)
{
form2 = new Form2(pictureBox1.Image);
form2.Show();
}
Form 2:
public Form2(Image pic1)
{
InitializeComponent();
pictureBox1.Image = pic1;
}
You are really asking two questions in one:
1 - How can I get the content of one PictureBox into another PictureBox?
2 - How can I access the controls etc. of one form from another form?
Question 1 is straightforward: pictureBox1.Image = pictureBox2.Image;
The answer to question 2 is not hard either but there are many ways to do it and selecting one may depend on what else you want to do with the two forms.
The basic way is always to get a valid reference to the other form.
Here is a general purpose method:
What is the right moment? Assuming form1 is created at the programm's startup and form2 is created by some action in form1 you could get the reference to form2 right there when you create and show it:
form2 = new Form2(this);
form2.Show();
This could be in a button click or even in the load event of form1.
Note that I have handed a reference to this
in the constructor! This is a nice way to pass the reference to form1 to the new form. Therefore the contructor in form2 should look like this:
public Form2(Form1 form1_)
{
InitializeComponent();
form1 = form1_;
}
The last step is to make the controls public which you need to access. Go to the Designer.cs file and change the declaration from
private System.Windows.Forms.PictureBox pictureBox1;
to
public System.Windows.Forms.PictureBox pictureBox1;
Done.
Or...
If you have many forms which all need to access the one PictureBox, you could also try this: Declare a static global reference to it in the programm.cs file like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static PictureBox thePictureBox;
Then fill in the reference in the form1
Program.thePictureBox = pictureBox1;
Now you can reference it in all other forms as well:
myNextPictureBox42.Image = Program.thePictureBox.Image;