I want to create two dimensional array of buttons in windows form. I have to do it with for loops because I want to have an array of 100 buttons. But I cant get it to work. I tried with List> and with Buttton[,] but doesn’t work. When I try like this:
private List<List<Button>> LEDarray = new List<List<Button>>();
for (int y = 0; y < 5; y++)
{
this.tempList.Clear();
for (int x = 0; x < 20; x++)
{
this.tempList.Add(new Button());
}
this.LEDarray.Add(tempList);
}
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 20; x++)
{
this.LEDarray[y][x].BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.LEDarray[y][x].FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.LEDarray[y][x].ForeColor = System.Drawing.Color.Black;
xPos = xOffset + LEDsize * x + 20;
yPos = yOffset + LEDsize * y + 20;
this.LEDarray[y][x].Location = new System.Drawing.Point(xPos, yPos);
this.LEDarray[y][x].Name = "button" + y.ToString() + x.ToString();
this.LEDarray[y][x].Size = new System.Drawing.Size(LEDsize, LEDsize);
this.LEDarray[y][x].TabIndex = 0;
this.LEDarray[y][x].UseVisualStyleBackColor = false;
}
}
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 20; x++)
{
this.Controls.Add(this.LEDarray[y][x]);
}
}
It only display the last row of buttons. So just fifth row and not the previous one. When I try similar with Button array it does not work at all. But array way is just SOS call. I want to do it with List so can you help me with code above to make it work?
Change condition
for (int y = 0; y < 0; y++)tofor (int y = 0; y < 5; y++)when adding buttons to controls.Second problem is that you are clearing your tempList, reference to which you just added to
LEDarray. Create new list for each row of buttons:Also I’d recommend you to increment
TabIndexfor buttons:And another advise – create your custom
LEDButtonclass and use it:Usage: