c# - 是否有一个嵌套循环来根据项目列表创建一个按钮网格?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;
}
解决方案
尝试以下:
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;
}
}
}
}
推荐阅读
- flutter - 正确布局列和扩展的小部件,没有有限的宽度
- c - 程序在捕获信号时冻结
- reactjs - 按下回车后如何请求远程数据?(mbrn/材料表)
- angular - 三个 js OBJ 加载器创建在 Angular 中的 typesecript 中不起作用
- angular - 传播类型只能从对象类型创建角度错误角度
- html - display flex 水平显示图像和完整段落,但无法正常工作
- javascript - 未捕获的 TypeError: $(...).fullCalendar 不是函数错误
- css - 如果选择了输入单选按钮,则显示 div
- mysql - 更新和选择 MYSQL
- javascript - 单击 youtube 播放按钮后触发事件