K
K
kos_dev2017-04-02 00:13:13
C++ / C#
kos_dev, 2017-04-02 00:13:13

How to determine which Control was clicked if it was created by code?

Hello, I am creating software that will dynamically add controls to a form.
Here is an example of creating a control:

Label label = new Label();
            label.ForeColor = Color.LightYellow;
            label.BackColor = Color.Transparent;
            label.AutoSize = false;
            label.Size = textSize;
            label.TextAlign = ContentAlignment.MiddleCenter;
            label.Text = _login;

            backPanel.Controls.Add(label);

The question is, so I created this label, now I want the number 0 to be written to the X variable by clicking on it, I will create another label, when I click on it, 1 is written in X. I think I conveyed the idea. I want to somehow distinguish between these labels so that, if necessary, I can remove one of them.
Thank you all in advance for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tom Nolane, 2017-04-02
@kos_dev

did you refer to the sender object when creating the button's Click method ?

private void button1_Click(object sender, EventArgs e)  
  {
  // тут какой-то код
  }

so, this sender is what you need, i.e.
private void label_Click(object sender, EventArgs e)  
  {
    Label lb = sender as Label;
      lb.Content = "какой-то текст";
// или 
     int x;
    switch((sender as Label).Name)
    { 
          case "label":  x = 0; break; 
          case "label2": x = 1; break; 
          case "label3": x = 2; break; 
          default: x = -1; break; 
    }
  }

that's all) sender - knows the object that was "clicked"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question