简体   繁体   English

为动态创建的Label添加控件

[英]Add Control for dynamically created Label

I am making a GUI Program which will display some path of files(according to the user input) Since, the labels are made according to the user input, they are created dynamically. 我正在制作一个GUI程序,它将显示一些文件路径(根据用户输入)因为标签是根据用户输入制作的,所以它们是动态创建的。 I want that when the user click on the label, the respective file is opened(whose text is displayed). 我希望当用户点击标签时,会打开相应的文件(显示其文本)。 I have stored all the labels created in a list. 我已经存储了列表中创建的所有标签。 I thought of the following solution to this problem 我想到了以下解决这个问题的方法

  • Add a Open function which will Open the file to the Click event 添加一个Open函数,将打开文件到Click事件

The problem is that 问题是
How the function will know which buttons text to use to open the file 该函数如何知道用于打开文件的文本按钮
ie If there are three lables , and user presses 2nd Label how will the Open function know which label is pressed? 即如果有三个标签,并且用户按下第二个标签,打开功能将如何知道按下哪个标签?

Give the labels unique names, assign them all the same click event, and use a switch: 为标签指定唯一名称,为它们分配所有相同的单击事件,并使用开关:

private void label_Click(object sender, EventArgs e)
{    
    switch(((Label)sender).Name)
    {
       case "Label1": 
            //........ 
          break;

    }
}

Edit: 编辑:

just subscribe to the event when you create your label: 只需在创建标签时订阅该事件:

label.Click += label_Click;

if you look at the Designer code, that's all it's doing when you set the event in the UI 如果您查看Designer代码,那么当您在UI中设置事件时,这就是它所做的一切

Finally, figured out a way 最后,想出办法

    private void LabelClick(object sender, EventArgs e)
    {
        string Path = ((Label)sender).Text ;
        System.Diagnostics.Process.Start(Path) ; 
     }

Here Path of the file is there in the Label's text property 这里文件的路径在Label的text属性中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM