[英]two dimensional array of buttons?
我想在Windows窗体中创建按钮的二维数组。 我必须使用for循环,因为我想拥有100个按钮的数组。 但是我无法使其正常工作。 我尝试使用List>和Buttton [,],但不起作用。 当我这样尝试时:
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]);
}
}
它仅显示按钮的最后一行。 所以只是第五行而不是前一行。 当我尝试使用Button数组进行类似操作时,它根本无法工作。 但是数组方式只是SOS调用。 我想用List来做,所以您能帮我做上面的代码以使其起作用吗?
将按钮添加到控件时,将for (int y = 0; y < 0; y++)
更改for (int y = 0; y < 5; y++)
。
第二个问题是您正在清除tempList,您刚刚将其添加到LEDarray
。 为每行按钮创建新列表:
for (int y = 0; y < 5; y++)
{
// tempList.Clear() - this will remove all buttons from previous row
tempList = new List<Button>();
for (int x = 0; x < 20; x++)
tempList.Add(new Button());
LEDarray.Add(tempList);
}
另外,我建议您增加按钮的TabIndex
:
this.LEDarray[y][x].TabIndex = 10 * y + x;
另一个建议-创建您的自定义LEDButton
类并使用它:
public class LEDButton : Button
{
public const int LEDWidth = 20;
public const int LEDHeight = 20;
public LEDButton()
{
BackColor = Color.FromArgb(0, 64, 0);
ForeColor = Color.Black;
FlatStyle = FlatStyle.Flat;
Size = new Size(LEDWidth, LEDHeight);
UseVisualStyleBackColor = false;
}
}
用法:
// initialize array
LEDButton[,] leds = new LEDButton[5, 20];
for (int y = 0; y < leds.GetUpperBound(0); y++)
for (int x = 0; x < leds.GetUpperBound(1); x++)
leds[y, x] = new LEDButton()
{
Name = String.Format("Button{0}{1}", y, x),
TabIndex = 10 * y + x,
Location = new Point(LEDButton.LEDWidth * x + 20,
LEDButton.LEDHeight * y + 20)
};
// add buttons to controls
for (int y = 0; y < leds.GetUpperBound(0); y++)
for (int x = 0; x < leds.GetUpperBound(1); x++)
Controls.Add(leds[y, x]);
由于您似乎混淆了边界值,请尝试使用foreach代替:-)
foreach (var row in this.LEDArray)
{
foreach (var button in row)
{
this.Controls.Add(button);
}
}
可以说,这可以更好地传达代码的意图-添加集合中的所有按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.