代码添加控件--button

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace pp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            addTable();
            Random r = new Random();
            for (int i = 0; i < 100; i++)
            {
                Button btn = new Button();
                btn.Text ="第"+(i+1)+ "个按钮";
                btn.BackColor = Color.LightBlue;
                btn.Dock = DockStyle.Fill;
                if (r.Next(0,100)%7==0)
                {
                    btn.Tag = 7;
                }
                else if(r.Next(0,100)%13==0)
                {
                    btn.Tag = 130;
                }
                else if (r.Next(0,100)%19==0)
                {
                    btn.Tag = 1900;
                }
                else
                {
                    btn.Tag = 0;
                }
                tableLayoutPanel1.Controls.Add(btn);
                btn.Click += btn_Click;
            }
           
        }
 
        void btn_Click(object sender, EventArgs e)
        {
            Button btn= sender as Button;
            btn.Text = btn.Tag.ToString();
 
            btn.Enabled = false;
        }
 
        private void addTable()
        {
            tableLayoutPanel1.ColumnStyles.Clear();
            tableLayoutPanel1.RowStyles.Clear();
            tableLayoutPanel1.ColumnCount = 10;
            for (int i = 0; i < 10; i++)
            {
                ColumnStyle style = new ColumnStyle(SizeType.Percent, 10);
                tableLayoutPanel1.ColumnStyles.Add(style);
            }
            tableLayoutPanel1.RowCount = 10;
            for (int i = 0; i < 10; i++)
            {
                RowStyle style = new RowStyle(SizeType.Percent, 10);
                tableLayoutPanel1.RowStyles.Add(style);
            }
 
        }
    }
}
原文地址:https://www.cnblogs.com/lovesy2413/p/4511160.html