Search code examples
c#event-handlinglabeladditioncreation

Cannot get label.text c#


I am new in C#, and now I have a problem that I cannot solve.

I have created the same label on multiple tabpages:

    public Label ChosenType = new Label();

    private void EvalType()
    {
        Label labelChosenType = new Label();
        labelChosenType.AutoSize = false;
        labelChosenType.Left = 710;
        labelChosenType.Top = 3;
        labelChosenType.Width = 350;
        labelChosenType.Height = 96;
        labelChosenType.Text = "Some text";
        labelChosenType.Font = new Font("Arial", 14, FontStyle.Bold);
        labelChosenType.TextAlign = ContentAlignment.MiddleCenter;
        labelChosenType.BackColor = Color.Red;
        labelChosenType.ForeColor = Color.White;
        labelChosenType.Click += new EventHandler(labelChosenType_Click);
        tabControl1.SelectedTab.Controls.Add(labelChosenType);
    }

   private void SetGeneralInfo()
    {           
        for (int i = 0; i < tabControl1.TabCount; i++)
        {
            tabControl1.SelectTab(i);
            EvalType();
        }
    }

    private void labelChosenType_Click(object sender, EventArgs e)
    {
        MessageBox.Show(labelChosenType.Text);
    }

The problem is that the messagebox is blank. Why can't I get the text from label? (This is not the main function, but this is simpliest way, to show the problem)

I have tried to add name like= "some text" + i, but it was the same on all tabs, and it didn't work.

Thank you!


Solution

  • Without seeing more code... my best guess is that the labelChoosenType you are referring to in the labelChooseType_Click() event handler is not the Label you think it is.

    Each new Label you add to the TabControl is a new Label - and not the Label referred to by labelChoosenType outside of the EvalType() method. So when you click on the Label, the text property refers to another object that you have not initialized using the EvalType() method.

    If you're trying to act on multiple objects of the same type in a single event handler, you're much better off using the object sender parameter. As it stands, it is totally unclear what object labelChoosenType refers to.

    private void labelChoosenType_Click(object sender, EventArgs e)
    {
        Label clickedLabel = sender as Label;
        if (clickedLabel != null)
        {
            MessageBox.Show(clickedLabel.Text);
        }
        else
        {
            // clickedLabel is not a Label or is null, do something else
        }
    }