下面是一个示例程序,演示如何动态生成Button控件并为其添加方法和属性:

using System;
using System.Windows.Forms;

namespace DynamicButtonDemo
{
    public partial class MainForm : Form
    {
        private int buttonCount = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            // 创建一个新的Button控件
            Button newButton = new Button();
            newButton.Text = "Button " + (++buttonCount);
            newButton.Location = new System.Drawing.Point(12, 12 + buttonCount * 30);

            // 为Button控件添加一个Click事件处理方法
            newButton.Click += new EventHandler(button_Click);

            // 为Button控件添加一个新的属性
            newButton.Tag = "This is button " + buttonCount;

            // 将Button控件添加到窗体中
            Controls.Add(newButton);
        }

        private void button_Click(object sender, EventArgs e)
        {
            // 显示Button控件的Tag属性值
            MessageBox.Show(((Button)sender).Tag.ToString());
        }
    }
}

这个程序包含一个按钮和一个空的窗体。当用户单击按钮时,程序会动态创建一个新的Button控件,并添加一个Click事件处理方法和一个新的Tag属性。单击这些动态生成的按钮时,程序会显示它们的Tag属性值


原文地址: https://www.cveoy.top/t/topic/fsxa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录