简体   繁体   中英

c# How to change the visible property of a label created at runtime

//Here I create the labels at runtime in one click

Label[] labels = new Label[countresult];

for (int i = 1; i < countresult; i++)
{
    labels[i] = new Label();
    labels[i].Font = new Font("Arial Rounded MT Bold", 30);
    labels[i].ForeColor = System.Drawing.Color.Red;
    labels[i].AutoSize = true;
    labels[i].Text = "";

    //Here I try to assign the value visible = true

    labels[i].Visible = true;
    labels[i].TabIndex = i;
}

//In a private void of a timer tick I assign the name of label to var "a" and I do the 3 methods

string a = string.Format("labels[{0}]", labelscount);

//1st method

if (this.Controls.ContainsKey(a))
{
    this.Controls[a].Visible=false;
}

//2nd method

foreach (Control control in Controls)
{
    if (control.Name == a)
    {
        control.Visible = false;
    }
}

//3rd method

if (this.Controls[a] is Label) this.Controls[a].Visible=false;
labelscount++;

Unfortunately none works.

Someone know What's happened?

You are not adding the labels to the owning control. So they will never be displayed. So in your loop you need to add the following as the last line...

this.Controls.Add(labels[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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