【问题标题】:c# How to change the visible property of a label created at runtimec#如何更改在运行时创建的标签的可见属性
【发布时间】:2015-03-30 00:08:55
【问题描述】:

//这里我在运行时一键创建标签

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;
}

//在计时器滴答的私有空白中,我将标签的名称分配给 var "a" 并执行 3 个方法

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

//第一种方法

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

//第二种方法

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

//第三种方法

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

不幸的是,没有任何工作。

有人知道发生了什么吗?

【问题讨论】:

  • 标签[i].Visible = false;您是否尝试过专门调用它?
  • 您是否真的将标签添加到父控件?
  • 是的,我尝试了,但是说当前上下文中不存在该名称

标签: c# label visible invisible


【解决方案1】:

您没有将标签添加到拥有控件。所以它们永远不会显示出来。因此,在您的循环中,您需要将以下内容添加为最后一行...

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

【讨论】:

  • 我在下一个 for 但什么也没用,看: for (int i = 0; i
  • 使用控件集合的索引而不是字符串名称。所以使用数字从集合中获取控件,this.Controls[3],而不是按名称。
  • 你说得对。这就是解决方案! @phil-wright 非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 2020-07-21
  • 2012-11-02
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 2014-05-05
相关资源
最近更新 更多