c# 如何用代码实现按钮的单击

2025-04-06 23:42:55
推荐回答(2个)
回答1:

c#中在代码中定义了一个Button控件,添加该控件的单击事件
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var lbl = new Label {Text = "LabelText"};
Controls.Add(lbl);
var but = new Button
{
Text = "ButtonText",
Tag = lbl,
Location = new Point(lbl.Location.X, lbl.Location.Y + lbl.Height)
};
but.Click += But_Click;
Controls.Add(but);
}
void But_Click(object sender, EventArgs e)
{
((Label) ((Button) sender).Tag).Text = "取消";
}
}
}

回答2:

首先是得到控件的ID 如BUTTION1 然后是他的属性最后是事件 如 Button1.Attributes.Add("onclick","函数名称");