首页 > 解决方案 > 是否有一个嵌套循环来根据项目列表创建一个按钮网格?C#

问题描述

我有一个项目列表,我需要遍历该列表中的每个项目并Button在 Windows 窗体上创建一个,我尝试了一个嵌套的 for 循环它不起作用,我正在尝试在网格中创建按钮。我只能像这样在一行上创建按钮:

int top = 0;
foreach (string name in buttonNames)
{
    Button pizzaControlButton = new Button();
    pizzaControlButton.Top = top * 50;
    pizzaControlButton.Left = 1;
    pizzaControlButton.Width = frmItems.btnStartingPointControls.Width;
    pizzaControlButton.Height = frmItems.btnStartingPointControls.Height;
    pizzaControlButton.Text = name;
    pizzaControlButton.Name = name;
    pizzaControlButton.Font = frmItems.Font;
    pizzaControlButton.ForeColor = Color.White;
    pizzaControlButton.BackColor = Color.Navy;

    frmItems.Controls.Add(pizzaControlButton);
    top += 1;
}

标签: c#

解决方案


尝试以下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace downloadstatuspage
{
    public partial class dowloadstatuspage : Form
    {
        const int WIDTH = 100;
        const int HEIGHT = 100;
        const int SPACE = 10;
        const int TOP = 10;

        public dowloadstatuspage()
        {
            InitializeComponent();

            string[] buttonNames = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M" };

            List<Button> pizzaButtons = new List<Button>();

            int size = (int)Math.Sqrt(buttonNames.Length);
            if (size * size != buttonNames.Length) size++; 

            int buttonCount = 0;
            for (int row = 0; row < size; row++)
            {
                for (int col = 0; col < size; col++)
                {
                    if (buttonCount == buttonNames.Length) break;

                    Button pizzaControlButton = new Button();
                    pizzaButtons.Add(pizzaControlButton);
                    this.Controls.Add(pizzaControlButton);

                    pizzaControlButton.Top = TOP + row * ( SPACE + HEIGHT);
                    pizzaControlButton.Left = col * (SPACE + WIDTH);
                    pizzaControlButton.Width = WIDTH;
                    pizzaControlButton.Height = HEIGHT;
                    pizzaControlButton.Text = buttonNames[buttonCount];
                    pizzaControlButton.Name = buttonNames[buttonCount];
                    pizzaControlButton.ForeColor = Color.White;
                    pizzaControlButton.BackColor = Color.Navy;

                    buttonCount++;
                }
                if (buttonCount == buttonNames.Length) break;
            }
        }
    }
}

推荐阅读