I have 2 forms, form1
and form2
. In form1 I call form2, where I input 2 numbers, one for height and for width of a picturebox. Then I want to pass that data from form2
to form1
, where I create picturebox with said size.
Then I want to store height and width to class and then access that info from form1
.
Here is my code:
Form1
namespace NPA_projekt
{
public partial class Form1 : Form
{
private Form2 f2 = new Form2();
image img = new image();
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
f2.ShowDialog();
}
private void btnTest_Click(object sender, EventArgs e)
{
pbMainArea.Width = img.width;
pbMainArea.Height = img.length;
}
}
}
Form2
namespace NPA_projekt
{
public partial class Form2 : Form
{
image img = new image();
public Form2()
{
InitializeComponent();
}
//reset btn
private void button1_Click(object sender, EventArgs e)
{
nudWidth.Value = 640;
nudLength.Value = 400;
}
//cancel btn
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
//ok btn
private void btnOK_Click(object sender, EventArgs e)
{
img.width = Convert.ToInt32(nudWidth.Value);
img.length = Convert.ToInt32(nudLength.Value);
this.Close();
}
}
}
Class image
namespace NPA_projekt
{
class image
{
public int width = 0;
public int length = 0;
}
}
Values, that are stored in form2
, are set to their original values, when I want to use them in form1
. Could someone please elaborate what's happening. Thank you all!
img
is declared twice. Once in Form1
and again in Form2
. When you are setting the width and height of img
in Form2
you are setting it for the image instance you declared in Form2
not Form1
. You need to make the img
in Form1
visible to Form2
and perform the operation on that.
So, make img
in Form1
public:
public image img {get; set;}
public Form1()
{
InitializeComponent();
img = new image();
}
Then you need to access it in Form2
(one way should be the Parent
property of the form):
private void btnOK_Click(object sender, EventArgs e)
{
var form1 = (Form1)this.Parent
form1.img.width = Convert.ToInt32(nudWidth.Value);
form1.img.length = Convert.ToInt32(nudLength.Value);
this.Close();
}
I haven't tested this all out, but the approach is valid. The key to eliminating the confusion is getting rid of the img
declaration in Form2
and realizing that you need to get access to Form1
from Form2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.