使用大量面板时出错:对象引用未设置为对象的实例
本文关键字:设置 对象引用 对象 实例 出错 | 更新日期: 2023-09-27 17:58:00
我想尝试使用几个面板。但这是错误的。当我单击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;
}
}
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;
}