[英]How can I pass a parameter to control event handler?
I am creating a winforms app which generates a number of panels at runtime. 我正在创建一个winforms应用程序,该应用程序在运行时会生成许多面板。 I want each panel, when clicked, to open a web link.
我希望每个面板在单击时都打开一个Web链接。
The panels are generated at runtime: 面板在运行时生成:
for (int i = 0; i < meetings.Count(); i++) {
Panel door = new Panel();
door.Location = new System.Drawing.Point((i * 146) + (i * 10) + 10, 10);
door.Size = new System.Drawing.Size(146, 300);
door.BackgroundImage = ConferenceToolkit.Properties.Resources.Door;
door.Click += new EventHandler(door_Click);
Controls.Add(door);
}
and I want the event handler to point to a URL that is stored somehow in the Panel attributes. 我希望事件处理程序指向以某种方式存储在Panel属性中的URL。 (On a web form I could use Attributes["myAttribute"] but this doesn't seem to work with WinForms):
(在Web窗体上,我可以使用Attributes [“ myAttribute”],但这似乎不适用于WinForms):
private void door_Click(object sender, EventArgs e)
{
Panel p = sender as Panel;
Process.Start(p.Attributes["url"]);
}
There are many options for this, you may store URL in the (unused in Panel
) Text
property: 有很多选项,您可以将URL存储在(在
Panel
未使用的) Text
属性中:
door.Text = FindUrl(meetings[i]);
Used like: 像这样使用:
Process.Start(p.Text);
As alternative you may use general purpose Tag
property: 或者,您可以使用通用
Tag
属性:
door.Tag = FindUrl(meetings[i]);
With: 带有:
Process.Start(p.Tag.ToString());
Tag property is usually right place for these things and, becauase it's of type object
, you can even use it to store complex types (in case you need more than a simple string). Tag属性通常是这些事情正确的地方 ,并becauase它的类型的
object
,你甚至可以用它来存储复杂类型(如果你需要的不仅仅是一个简单的字符串更多)。
See also similar posts for slightly more complex cases: this , this and this . 对于稍微复杂一些的案例,请参见类似的帖子: this , this和this 。
You can store the URL that you want in the Panel's Tag propertie 您可以将所需的URL存储在面板的标签属性中
for example 例如
p.Tag = "www.google.com";
and then you can use it when use cast the Panel in the on click method 然后您可以在使用on click方法时投射面板时使用它
reference for the .Tag property .Tag属性的参考
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag(v=vs.110).aspx http://msdn.microsoft.com/zh-CN/library/system.windows.forms.control.tag(v=vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.