Pratik Singhal
Pratik Singhal

Reputation: 6492

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. 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

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?

Upvotes: 0

Views: 69

Answers (2)

Pratik Singhal
Pratik Singhal

Reputation: 6492

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

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

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

Upvotes: 2

Related Questions