如何处理以编程方式添加的组件事件?
你好朋友,
我正在以编程方式创建图片框。通过我在表格上添加图片框。一切都很好。但现在我想处理那些图片盒的事件。我没有得到它。如果没有在设计部分的表单上添加控件,那么我如何获得这些控件的事件?我在表单加载事件中添加了表单上的控件。
plzz帮助我...
hello friends,
I am creating pictureboxes programmatically. coading through i am adding the pictureboxes on a form. Everything is working fine. But now i want to handle events of those pictureboxes. I'm not getting it. if controls are not added on form in design part, then how can i get the events of those controls? I'm adding those controls on form at the form loading event.
plzz help me out...
这取决于你如何在设计时预测事件处理程序代码。
比方说,你将有几个控件,它们会做同样的但是他们的数量可能会根据用户需求而有所不同在这种情况下,您可以在设计时编写事件处理程序,就像常规方法一样。如果你看一下VS生成的代码,你会发现它也是这样做的:
It depends how you can predict the event handler code on design time.
Let's say, you will have several controls, that will do the same but their number may vary based on user needs. In that case, you can write the event handler at design time just as a normal method. If you look at the code generated by VS, you will see that it is doing the same:
this.button1.Click += new System.EventHandler(this.button1_Click);
虽然有一个
While there is a
private void button1_Click(object sender, EventArgs e)
{
...
}
在某处定义。
现在,您可以将此方法命名为 GeneralButtonClick
处理程序并指定它任意数量的按钮点击事件 - 实际上你可以这样做而不重命名它,这只是为了说明。
defined somewhere.
Now, you could name this method GeneralButtonClick
handler and assign it to any number of button click events - actually you could do this without renaming it, this was only for illustration.
this.button2.Click += new System.EventHandler(this.button1_Click);
this.button3.Click += new System.EventHandler(this.button1_Click);
但要注意使用(使方法体对上下文敏感,与控制对象的变量名无关)发件人为System.Windows.Forms.Button)
构造而不是 button1
。
您可以使用此方法图片框也是。
这是一个更复杂的情况,你无法在设计时告诉事件处理程序将做什么。比你将写并动态编译事件处理程序方法。但是,只有在这种情况下才让我们谈谈它。
But be aware to make the method body context-sensitive and not related to the control object's variable name, by using (sender as System.Windows.Forms.Button)
constructs instead of button1
.
You can follow this approach with your picturebox too.
It is a more complex situation where you can't tell at design time what the event handler will do. Than you will have do "write" and compile the event handler method on the fly. But let's talk about it only if this is the case.