My program consists of 3 static buttons created using WinForms: button1, button2 and button3. Buttons 2 and 3 are set to enabled=False. What I want to do is enable these 2 buttons in turn by clicking on button 1 by placing them in an array. This is my code so far but does not work. Can anyone see what I’m doing wrong?
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Button[] btns = new Button[2];
//Button[] btns = { button2}
public Form1()
{
InitializeComponent();
Button[] btns = { button2, button3};
}
private void Form1_Load(object sender, EventArgs e)
{
button2.Enabled = false;
button3.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 2; i++)
{
// btns[i] = new Button();
//btns[i].Enabled = true;
}
}
}
}
The main problem in the code in the question is here:
The problem is that inside the
Form1constructor,btnsis a local variable. Your code clearly assumes that you are referring to the member variable of the same name.So you initialize the local variable, and then it immediately vanishes out of scope. In the rest of the code you refer to the member variable
btnswhich has not initialised.Solve the problem by initialising that member variable. You could do it like this: