简体   繁体   中英

TableLayoutPanel loop (C# forms)

I have 3x3 grid with labels in every cell and Text "X" in each and every one. When I click on one of these labels, I want the one and the one next to it to change the text to "O" by using foreach loop of controls (rows and columns). Does anyone have an idea of what it would have to look like?

This is certainly not a full solution, but maybe it'll give you an idea on how to start.

To create the labels, you'll certainly want to do that programatically:

  for (int col = 0; col < table.ColumnCount; col++)
  {
    for (int row = 0; row < table.RowCount; row++)
    {
      Label lbl = new Label();
      lbl.Click += Lbl_Click;
      table.Controls.Add(lbl, col, row);
    }
  }

Note that the click event is the same for every label. Within that event you can get information about the label that was clicked:

private void Lbl_Click(object sender, EventArgs e)
{
  Label lbl = (Label)sender;
  int row = table.GetRow(lbl);
  int col = table.GetColumn(lbl);

  lbl.Text = "O";

  //This is just an example
  //This will throw an error if you click the rightmost cell
  Label lbl2 = (Label)table.GetControlFromPosition(col+1,row);
  lbl2.Text = "O"; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM