Search code examples
c#imagepictureboxwindows-forms-designer

Trouble loading images in windows forms C#


I have 2 windowsForms lets call them form1 and form2. form1 consists of a picturebox and a button. When I click on the button form2 opens. Now form2 consists of a grid and depending on the position on which I have clicked on the grid the x and y coordinates are returned to form1. Based on these coordinates I add an image to the pictureBox. But the image isn't getting added! Is there something I am missing here?

Code inside the mouseDownEvent in form2

Form1 f1 = new Form1();
f1.openImage(x,y);

Code in form1

internal void openImage(int x, int y)
    {
        string ogFileName = "r" + x.ToString() + "c" + y.ToString();
        string imageFilePath = ogFileName  + "." + extension;
        MessageBox.Show(imageFilePath); //I can see the correct path here
        pictureBox1.Image = Image.FromFile(imageFilePath);
}//extension is a static variable declared outside this function.

Solution

  • Form1 f1 = new Form1();
    

    This line only creates a new instance of Form1

    What you can do is adding a Form1 variable which will reference your current form.

    You initialize it in constructor and in the button click you pass it to Form2

    public partial class Form1 : Form
    {
       Form1 form1; // form1 will store the reference of Form1
       public Form1()
       {
        form1 = this; // We initialize form1 in the constructor
        InitializeComponent();
       }
    
       // button to open form2
       private void button1_Click(object sender, EventArgs e)
       {
           Form2 form2 = new Form2(form1); // We open form2 with form1 as parameter
            form2.Visible = true;
        }
    
    
        public void openImage(int x, int y)
        {
    
        }
    
    }
    

    Now in the Form2 you just have to add a Form1 variable that will be initialized in the constructor.

    Then you can use it as now it represents the current instance of Form1

    public partial class Form2 : Form
    {
        Form1 form1; // Reference to form1
    
        public Form2(Form1 form1)
        {
            this.form1 = form1; // We initialize form1
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            // we call openimage from form1
            form1.openImage(130, 140);
        }
    }
    

    I have tested this example with a label and it works fine so I think there should be no problem with a picturebox