Ron Amme Ron Amme - 2 months ago 18
C# Question

Lights Out C# Multidimensional Array

So yeah we have the Lights out Game to program

Button[,] lights = new Button[5,5];

for (int i = 0; i < lights.GetLength(1); i++)
{
for (int j = 0; j < lights.GetLength(0); j++)
{
lights[i, j] = new Button();
lights[i, j].Size = new System.Drawing.Size(50, 50);
lights[i, j].Click += (sender, args) => light_OnOff(lights[i,j], i, j);
lights[i, j].BackColor = Color.Yellow;
lightPanel.Controls.Add(lights[i, j]);

MessageBox.Show("I:"+Convert.ToString(i) + "J:" +Convert.ToString(j));
}
}
}

public void light_OnOff(object sender, int i, int j)
{
if(lights[i, j].BackColor == Color.Yellow)
{
lights[i, j].BackColor = Color.Black;
}
}
}
}


The Problem i am having right now is that it says its out of Array Range (the index) but i dont know why. Maybe you could help me.

Answer

Instead of creating event with your way, set button's name to seperate them from each other.

        for (int i = 0; i < lights.GetLength(1); i++)
        {
            for (int j = 0; j < lights.GetLength(0); j++)
            {
                lights[i, j] = new Button();
                lights[i, j].Size = new System.Drawing.Size(50, 50);
                lights[i, j].Name = "button" + i.ToString() + j.ToString(); // set name like this
                lights[i, j].Click += autoGeneratedEventName_Click; //after "+=" hit tab twice visual studio will create event auto;
                lights[i,j].Location = new Point(40 + (j*70), 20 + (i * 70));
                lights[i, j].BackColor = Color.Yellow;
                this.panel1.Controls.Add(lights[i, j]);

                //MessageBox.Show("I:" + Convert.ToString(i) + "J:" + Convert.ToString(j));
            }
        } 

And at the event, sender will solve the problem, you don't need to send the array's indexes to event. (also you can find the indexes from buttons last 2 name)

private void autoGeneratedEventName_Click(object sender, EventArgs e)
        {
            Button b = sender as Button; //Clicked object is a Button
            if (b.BackColor == Color.Yellow) 
            {
                b.BackColor = Color.Black;
            }
            label1.Text = b.Name;
        }

Result;

enter image description here

Hope helps,

Comments