使用大量面板时出错:对象引用未设置为对象的实例

时间:2014-04-11 16:48:46

标签: c# winforms

我想尝试使用几个面板。但是有错误。当我点击button_1时,它应该显示一个面板并隐藏另一个面板。我在Form_Load中初始化我的面板。这是我的代码:

public partial class Form1 : Form
    {
        public Panel[] p = new Panel[2];
        public int iter = 1;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (iter%2 == 1)
            {
                p[0].Visible = true;
                p[1].Visible = false;
            }
            else if (iter%2 == 0)
            {
                p[0].Visible = false;
                p[1].Visible = true;            

            }
            iter++;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 2; i++)
            {
                p[i] = new Panel();
                p[i].Visible = false;
                p[i].Size = new Size(200, 100);
                p[i].Location = new Point(41, 103);
            }
            p[0].BackColor = System.Drawing.Color.Red;
            p[1].BackColor = System.Drawing.Color.Blue;
        }
    }

1 个答案:

答案 0 :(得分:0)

private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 2; i++)
    {
        p[i] = new Panel();
        p[i].Visible = false;
        p[i].Size = new Size(200, 100);
        p[i].Location = new Point(41, 103);
        this.Controls.Add(p[i]);   // You need this line to add panel to form
    }
    p[0].BackColor = System.Drawing.Color.Red;
    p[1].BackColor = System.Drawing.Color.Blue;
}