1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Drawing;
5 using System.Data;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 namespace 方格练习
11 {
12 public partial class FillBtn : UserControl
13 {
14 public FillBtn()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /// 填充按钮
20 /// </summary>
21 /// <param name="btnNum">按钮数量</param>
22 public void FillButton(int btnNum)
23 {
24 //填充btnNum*btnNum个方格,现在放置的是罗列着的
25 for (int i = 0; i < btnNum * btnNum; i++)
26 {
27 Button btn = new Button();
28 this.Controls.Add(btn);
29 }
30 //定义方法,因为需要改变大小,所以单独
31 this.LayoutBtns();
32 }
33 /// <summary>
34 /// 布局按钮
35 /// </summary>
36 /// <returns></returns>
37 private void LayoutBtns()
38 {
39 //去除启动状态,以免开启的时候FillBtn_SizeChanged会报错
40 if (this.Controls.Count==0)
41 {
42 return;
43 }
44 //循环多少次?计算出来
45 int btnLineNum = (int)Math.Sqrt(this.Controls.Count);
46 //计算按钮的宽度
47 int btnWidth = this.Width / btnLineNum;
48 int btnHeight = this.Height / btnLineNum;
49
50 int btnIndex = 0;
51 int btnX = 0, btnY = 0;
52 //竖向的循环嵌套横着的循环
53 for (int verticalIndex = 0; verticalIndex < btnLineNum; verticalIndex++)
54 {
55 btnY = verticalIndex * btnHeight;
56 //水平向的循环
57 for (int horizontalIndex = 0; horizontalIndex < btnLineNum; horizontalIndex++)
58 {
59 btnX = horizontalIndex * btnWidth;
60 //获取要放置的方格
61 Button btn = this.Controls[btnIndex] as Button;
62 //设置当前方格的大小
63 btn.Size = new Size(btnWidth, btnHeight);
64 //设置当前方格的位置
65 btn.Location = new Point(btnX, btnY);
66 //下一个方格
67 btnIndex++;
68 }
69 }
70 }
71
72 private void FillBtn_SizeChanged(object sender, EventArgs e)
73 {
74 //设置当控件大小改变时的事件
75 this.LayoutBtns();
76 }
77 }
78 }