How can I change something in Form1 from DialogBox?

Suppose I have two forms (Form1 and Form2).

  • Form1 has a PictureBox
  • Form2 I have an OpenFileDialog

Form 1 is the main form, so when I start the project, I see Form1.

How to change image in PictureBox in Form1 from Form2?

+3
source share
5 answers

You can do it very simply. First, change your code (in Form1) that shows Form2 so that it looks like this:

<variable-of-type-Form2>.ShowDialog(this);

or if you do not want form2 to be modal

<variable-of-type-Form2>.Show(this);

Further, when you have a path to the image, you can access the PictureBox, like this

((PictureBox)this.Owner.Controls["pictureBox1"]).Image=Image.FromFile(<filename>);

Suppose you have a PictureBox in Form1 named "pictureBox1"

+1
source

?

, , , .

+2

, . , , , , .

, . SetImage() . form1.SetImage().

[]

, OpenFileDialog, , .

:

private void button1_Click(object sender, EventArgs e)
{
    using (var dialog = new OpenFileDialog())
    {
        var result = dialog.ShowDialog();
        if (result != DialogResult.OK)
            return;
        pictureBox1.Image = Image.FromFile(dialog.FileName);
    }
}

Form1.

[]

, .

public class MyForm1 : Form
{
    public MyForm1()
    {
        InitializeComponent();
    }

    public void SetImage(Image image)
    {
        pictureBox1.Image = image;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2(this);
        form2.Show();
    }
}

public class MyForm2 : Form
{
    private MyForm1 form1;

    public MyForm2()
    {
        InitializeComponent();
    }

    public MyForm2(MyForm1 form1)
    {
        this.form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form1.SetImage(yourImage);
    }
}
+2

Program.cs , FormOptions, .

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var frm = new Form1();
        // Add the code to set the picturebox image url
        Application.Run(frm);
    }

, Form1 .

+2

ModelViewController. . OpenFileDialog Form2, , (Form1 Form2), , . , . , MVC, , , Form1, Form2 , .

+1

All Articles