I'm developing a demo that, for now, simply changes the width and height of a PictureBox according to the user's input.
For this to happen, the user inputs the data in one Windows Forms, and the PictureBox is in another PictureBox.
They exchange data via constructor as exemplified by this code:
if (pf.GetData().Item1 >= int.Parse(textBox1.Text) && pf.GetData().Item2 >= int.Parse(textBox2.Text))
{
PictureForm pbf = new PictureForm(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
pf.Show();
this.Hide();
}
in the first Form
public PictureForm(int newMaxX, int newMaxY)
{
pictureBox1.Width = newMaxX;
pictureBox1.Height = newMaxY;
}
and the constructor.
When I debut and input everything, this error message shows:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
pictureBox1 was null.
I really don't understand what's wrong. Can somebody help me with this?
CodePudding user response:
In the form constructor, you must call InitializeComponent
. This creates and configures the controls.
public PictureForm(int newMaxX, int newMaxY)
{
InitializeComponent();
pictureBox1.Width = newMaxX;
pictureBox1.Height = newMaxY;
}
The form is implemented with partial classes. I.e., the Form class is split into two code files: PictureForm.cs
(this is where your user code resides) and PictureForm.designer.cs
. The latter is created by the forms designer and contains the method InitializeComponent
. You can open this file and look what this method does. All the controls with all their properties are created here. This is what is saved, when you save a form. I.e., there is no mysterious file format where the form is stored because everything is stored as C# code (except for resources, like icons that are stored in PictureForm.resx
).