在运行时将 PictureBox 添加到窗体

Add PictureBox to form at runtime

我正在制作一个将生成 PictureBox 的 C# 程序:

private void Form1_Load(object sender, EventArgs e)
{
    PictureBox picture = new PictureBox
    {
        Name = "pictureBox",
        Size = new Size(16, 16),
        Location = new Point(100, 100),
        Image = Image.FromFile("hello.jpg"),
    };
}

但是,该控件没有显示在我的表单上。为什么不呢?

一个控件,例如 PictureBox,就是一个 class。它没有什么特别之处,所以 new PictureBox 不会神奇地出现在您的表单上。

实例化和初始化控件后,您需要做的就是将控件添加到容器的 Controls 集合中:

this.Controls.Add(picture);

你可以试试这个.. 你需要使用 this.Controls.Add(图片);

private void Form1_Load(object sender, EventArgs e)
    {
        var picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(16, 16),
            Location = new Point(100, 100),
            Image = Image.FromFile("hello.jpg"),

        };
        this.Controls.Add(picture);
    }

如果您想在运行时从表单中删除。

 //remove from form
 this.Controls.Remove(picture);
  //release memory by disposing
 picture.Dispose();

;