简体   繁体   English

TableLayoutPanel 循环(C# 表单)

[英]TableLayoutPanel loop (C# forms)

I have 3x3 grid with labels in every cell and Text "X" in each and every one.我有 3x3 网格,每个单元格都有标签,每个单元格都有文本“X”。 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).当我单击其中一个标签时,我希望它旁边的一个和一个通过使用 foreach 控件循环(行和列)将文本更改为“O”。 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.请注意,每个 label 的点击事件都是相同的。 Within that event you can get information about the label that was clicked:在该事件中,您可以获得有关被点击的 label 的信息:

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"; 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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