您的位置:首页 > 编程语言 > C#

C#winform中动态添加button并绑定事件

2015-03-06 16:44 417 查看
<strong><span style="font-size:18px;">最近做的项目中用到的,新手很多不懂的地方,一点一点学习弄出来的,记录一下</span></strong>
<pre class="csharp" name="code"><strong><span style="font-size:18px;">private void treeView_Apps_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (MessageBox.Show("确定要安装此APP吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
//MessageBox.Show("1234");
if (e.Node.Tag is App)
{
treeView1.SelectedNode = e.Node;
App app = e.Node.Tag as App;
Button AppButton = new Button();
this.flowLayoutPanel1.Controls.Add(AppButton);
AppButton.Text = app.AppName;
AppButton.Tag = app.AppAddress;
AppButton.MouseClick += new MouseEventHandler(button_MouseClick);
AppButton.Size = new System.Drawing.Size(66, 66);
AppButton.UseVisualStyleBackColor = true;
}
}
}
private void button_MouseClick(object sender , MouseEventArgs e)
{
Button button = (Button)sender;
string path = button.Tag.ToString();
System.Diagnostics.Process.Start(path);
}</span></strong>



<strong><span style="font-size:18px;">首先是动态添加按钮,是在一个treeview点击事件中完成的,添加到winform上的flowlayoutpanel控件上。</span></strong>

App是自己写的一个类,跟按钮对应一些属性。

然后给按钮绑定下面的点击事件,Button button = (Button)sender是其中的关键,sender代表发生事件的对象,这样就可以通过这里的button来调用上面的AppButton的属性了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: