如何解决picturebox1为null?

How to solve picturebox1 is null?

我正在开发一个演示,目前,它只是根据用户的输入更改 PictureBox 的宽度和高度。

为此,用户在一个 Windows 表单中输入数据,而 PictureBox 在另一个 PictureBox 中。

它们通过构造函数交换数据,如下代码所示:

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();
}

第一种形式

public PictureForm(int newMaxX, int newMaxY)
{
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}

和构造函数。

当我首次亮相并输入所有内容时,此错误消息显示:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

pictureBox1 was null.

我真的不明白这是怎么回事。 有人可以帮我解决这个问题吗?

在表单构造函数中,必须调用InitializeComponent。这将创建和配置控件。

public PictureForm(int newMaxX, int newMaxY)
{
    InitializeComponent();
    pictureBox1.Width = newMaxX;
    pictureBox1.Height = newMaxY;
}

表单是使用部分 classes 实现的。即,表单 class 被分成两个代码文件:PictureForm.cs(这是您的用户代码所在的位置)和 PictureForm.designer.cs。后者由表单设计器创建并包含方法 InitializeComponent。您可以打开此文件并查看此方法的作用。所有具有所有属性的控件都在这里创建。这是保存表单时保存的内容。也就是说,没有神秘的文件格式存储表单,因为所有内容都存储为 C# 代码(资源除外,例如存储在 PictureForm.resx 中的图标)。