これは、実行時にラベルが作成されるソリューションです。「マトリックス」とボタンをホストするパネルが必要で、すべてデフォルト名が付いています。ボタンをクリックするとチェッカーボードが描画され、各セルをクリックすると色を反転できます。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const int RowCount = 6;
const int ColumnCount = 8;
private void button1_Click(System.Object sender, System.EventArgs e)
{
for (int i = 0; i < RowCount; i++)
{
for (int j = 0; j < ColumnCount; j++)
{
Label lbl = new Label();
lbl.Size = new Size(20, 20);
lbl.Location = new Point(i * 20, j * 20);
lbl.BackColor = (i + j) % 2 == 0 ? Color.Black : Color.White;
lbl.Click += lbl_Click;
panel1.Controls.Add(lbl);
}
}
MessageBox.Show(CountCellsOfColor(Color.Black).ToString());
}
private int CountCellsOfColor(Color color)
{
int count = 0;
foreach (Label lbl in panel1.Controls.OfType<Label>())
{
if (lbl.BackColor == color) count += 1;
}
return count;
}
private void lbl_Click(object sender, System.EventArgs e)
{
Label lbl = (Label)sender;
Color color = lbl.BackColor;
if (color == System.Drawing.Color.Black)
{
color = System.Drawing.Color.White;
}
else
{
color = System.Drawing.Color.Black;
}
lbl.BackColor = color;
}
}
VB.NET バージョン (元のバージョン、後で C# に変換されましたが、必要な場合に備えて保持することにしました):
Option Strict On
Public Class Form1
Const RowCount As Integer = 6
Const ColumnCount As Integer = 8
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
For i = 0 To RowCount - 1
For j = 0 To ColumnCount - 1
Dim lbl As New Label
lbl.Size = New Size(20, 20)
lbl.Location = New Point(i * 20, j * 20)
lbl.BackColor = If((i + j) Mod 2 = 0, Color.Black, Color.White)
AddHandler lbl.Click, AddressOf lbl_Click
Panel1.Controls.Add(lbl)
Next
Next
MessageBox.Show(CountCellsOfColor(Color.Black))
End Sub
Private Function CountCellsOfColor(color As Color) As Integer
Dim count As Integer = 0
For Each lbl In Panel1.Controls.OfType(Of Label)()
If lbl.BackColor = color Then count += 1
Next
Return count
End Function
Private Sub lbl_Click(sender As Object, e As System.EventArgs)
Dim lbl As Label = CType(sender, Label)
Dim color As Color = lbl.BackColor
If color = Drawing.Color.Black Then
color = Drawing.Color.White
Else
color = Drawing.Color.Black
End If
lbl.BackColor = color
End Sub
End Class