C#添加控件+注册事件(示例)

时间:2024-02-23 13:05:36

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 MyTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "选中了";        //按钮文字
            Button newButton=new Button();  //新建一个按钮控件
            newButton.Text = "新按钮";      //为新按钮添加文字
            this.Controls.Add(newButton);   //将控件添加到窗体中
            newButton.Click+=new EventHandler(newButton_Click);//将单击事件注册,以便监听

        }
        private void newButton_Click(object sender,EventArgs e)//监听单击事件
        {
            Button bt = (Button)sender;
            bt.Text = "点我了";
        }
    }
}

//////////////////////////////////////////////

运行效果:

运行后

单击button1

单击新按钮