[英]How to solve picturebox1 is null?
I'm developing a demo that, for now, simply changes the width and height of a PictureBox according to the user's input.我正在开发一个演示,目前,它只是根据用户的输入更改 PictureBox 的宽度和高度。
For this to happen, the user inputs the data in one Windows Forms, and the PictureBox is in another PictureBox.为此,用户在一个 Windows Forms 中输入数据,而 PictureBox 在另一个 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.'
System.NullReferenceException:“对象引用未设置为 object 的实例。”
pictureBox1 was null.
pictureBox1 是 null。
I really don't understand what's wrong.我真的不明白怎么了。 Can somebody help me with this?
有人可以帮我吗?
In the form constructor, you must call InitializeComponent
.在表单构造函数中,您必须调用
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.表单是用分部类实现的。 Ie, the Form class is split into two code files:
PictureForm.cs
(this is where your user code resides) and PictureForm.designer.cs
.即,表单 class 被分成两个代码文件:
PictureForm.cs
(这是您的用户代码所在的位置)和PictureForm.designer.cs
。 The latter is created by the forms designer and contains the method InitializeComponent
.后者由 forms 设计者创建并包含
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.
这是保存表单时保存的内容。 Ie, 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
).即,存储表单的地方没有神秘的文件格式,因为所有内容都存储为 C# 代码(资源除外,例如存储在
PictureForm.resx
中的图标)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.