【问题标题】:traverse a GUI button grid in c#在 C# 中遍历 GUI 按钮网格
【发布时间】:2020-05-08 22:05:24
【问题描述】:

最近我用 c# 创建了一个数独求解程序,现在我正在尝试根据我最近的代码创建一个可视 GUI 数独游戏。现在我将按钮放置在面板中,并看到我可以像这样遍历面板中的按钮:

 foreach (Button b in this.gamePanel.Controls);

但是,遍历似乎是随机的,有没有办法像遍历矩阵一样在 2 个 for 循环中遍历这些按钮?

非常感谢 :) The buttons grid I created

【问题讨论】:

  • 如果你的面板是普通的Panel,那么你不能,控件的顺序就是它们被添加的顺序。也许您可以标记按钮以找出它们在矩阵方面的位置。
  • 我通常会创建一个 List> 游戏并将按钮添加到列表中。该列表只是链接到您现有的控件,您可以通过列表或单独访问按钮并读取/更改相同的对象。
  • 假设我标记了他们如何使用 ???标记?
  • @jdweng 你是否有一个代码示例来说明如何做到这一点?这是我在 c# 中的第一个 GUI 项目,我已经在 J​​avaFX 中做了一些 GUI,但这里似乎有所不同

标签: c# user-interface


【解决方案1】:

尝试以下:

    public partial class Form1 : Form
    {
        const int WIDTH = 60;
        const int HEIGHT = 60;
        const int SPACE = 3;
        const int ROWS = 9;
        const int COLS = 9;
        List<List<Button>> buttons = new List<List<Button>>();
        public Form1()
        {
            InitializeComponent();

            for (int row = 0; row < ROWS; row++)
            {
                List<Button> newRow = new List<Button>();
                buttons.Add(newRow);
                for (int col = 0; col < COLS; col++)
                {
                    Button newButton = new Button();
                    newButton.Width = WIDTH;
                    newButton.Height = HEIGHT;
                    newButton.Top = row * (HEIGHT + SPACE);
                    newButton.Left = col * (WIDTH + SPACE);
                    newButton.BackColor = (row / 3 + col / 3) % 2 == 0 ? Color.Red : Color.Black;
                    newRow.Add(newButton);
                    panel1.Controls.Add(newButton);
                }
            }


        }
    }

【讨论】:

  • 太棒了,我现在就试试。谢谢
  • 我为按钮添加了背景颜色。
  • 我实际上使用了一种不同的方法来为行添加颜色: if(row % 3 == 0 and row != 0 ) change color for cols: if(col % 3 == 0 and col ! = 0 ) 改变颜色,但你的方式看起来也不错
猜你喜欢
  • 1970-01-01
  • 2015-10-09
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 2021-05-31
  • 2011-10-28
相关资源
最近更新 更多