如何控制动态添加的usercontrol

本文关键字:动态 添加 usercontrol 控制 何控制 | 更新日期: 2023-09-27 18:05:23

我有一个这样的代码:

MyUserControl[] myControl = new MyUserControl[10];

当Form load:

for( int i = 0; i < 10; i++ )
{
    myControl[i] = new MyUserControl();
    myControl[i].label1.Text = "Title";
    this.Controls.Add ( myControl[i] );
}

现在显示正常。

然后按下下面的按钮:

private void Button1_Click(object sender, EventArgs e)
{
    myControl[0].label1.Text = "Other Title";
}

当我看到调试模式时,值正常添加,但lable1文本不显示"其他标题"。

所以,我尝试下面的方法,但没有任何工作。

myControl[0].label1.Update();
myControl[0].label1.Invalidate();
myControl[0].label1.Refresh();

请告知。

如何控制动态添加的usercontrol

我不明白你的概念希望这个例子对你有用

private void Button1_Click(object sender, EventArgs e)
{
    //myControl[0].label1.Text = "Other Title";
    MyUserControl ctrl = null;
    foreach (var c in this.Controls)
    {
        if (c.GetType().Name == "MyUserControl")
        {
            var myctrl = (MyUserControl)c;
            if (myctrl.Text == "Title")
            {
                ctrl = myctrl;
                break;
            }
        }
    }
    if (ctrl != null)
    {
        ctrl.Text = "Other Title";
    }
}

这是一个非常简单的例子,代码将工作,你必须增强你喜欢

谢谢大家。这件事我有一个根本原因。

myControl[0].label1.Text = "Other Title";
myControl[0].BringToFront(); // <- Solved problem with this code.

我不知道为什么z-order是扭曲的