将图片框添加到面板

时间:2017-09-07 19:22:09

标签: c# winforms panel picturebox

我有一个包含面板(称为panel1)的Windows窗体应用程序和一个按钮。我点击按钮时尝试添加并显示新的PictureBox,但我无法使用我的代码。

private void button1_Click_1(object sender, EventArgs e)
{
    PictureBox picture = new PictureBox();
    picture.Location = new System.Drawing.Point(0, 0);
    picture.Name = "pictureBox1";
    picture.Size = new System.Drawing.Size(75, 50);
    picture.BackColor = Color.Black;
    panel1.Controls.Add(pictureBox1);
}

我的面板`Dock设置为Fill。

完整代码:https://pastebin.com/v73mZ9Ua

- 更新 -

我刚刚意识到我的错误:我使用了错误的变量名:panel1.Controls.Add(pictureBox1);什么时候应该是panel1.Controls.Add(图片);

1 个答案:

答案 0 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PictureBox pictureBox1 = new PictureBox();


        }
     private void button1_Click_1(object sender, EventArgs e)
        {   
            pictureBox1.Location = new System.Drawing.Point(50,50);
            pictureBox1.Name = "pictureBox1";
            pictureBox1.Size = new System.Drawing.Size(75, 50);
            pictureBox1.BackColor = Color.Black;
            panel1.Controls.Add(pictureBox1);
    }

}