Reputation: 908
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;
}
}
}
}
Upvotes: 0
Views: 1244
Reputation: 612954
The main problem in the code in the question is here:
public Form1()
{
InitializeComponent();
Button[] btns = { button2, button3};
}
The problem is that inside the Form1
constructor, btns
is 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 btns
which has not initialised.
Solve the problem by initialising that member variable. You could do it like this:
public partial class Form1 : Form
{
private Button[] btns;
public Form1()
{
InitializeComponent();
btns = new Button[] { button2, button3 };
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (var btn in btns)
{
btn.Enabled = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (var btn in btns)
{
if (!btn.Enabled)
{
btn.Enabled = true;
return;
}
}
}
}
Upvotes: 4
Reputation: 152541
Indexes are 0-based by default, not 1-based. This should work:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 2; i++)
{
btns[i].Enabled = true;
}
}
or use foreach
:
private void button1_Click(object sender, EventArgs e)
{
foreach(Button btn in btns)
{
btn.Enabled = true;
}
}
Also your array initialization should be:
Button[] btns = new [] { button2, button3};
Upvotes: 3