简体   繁体   English

如何控制动态添加的usercontrol?

[英]How to control that dynamically added usercontrol?

I have a code like this: 我有这样的代码:

MyUserControl[] myControl = new MyUserControl[10];

when Form load: 加载表单时:

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

    this.Controls.Add ( myControl[i] );
}

now it is show normally. 现在正常显示。

after then press button like below: 之后按如下按钮:

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

When i see the debug mode,value was added normally, but lable1 text not show "Other Title". 当我看到调试模式时,通常会添加值,但是lable1文本不会显示“其他标题”。

So, I try to below method, but not work anything. 所以,我尝试下面的方法,但是什么也没用。

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

Please, kindly advise. 请,请指教。

I don't understand your concept Hope this example work for you 我不明白您的想法希望这个例子对您有用

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

This is a very simple example that code will work and you have to enhance as you like 这是一个非常简单的示例,代码可以正常工作,您必须根据需要进行增强

Thank you for everyone. 谢谢大家 I got a root cause in this matter. 我在这件事上有根本原因。

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

I don't know why z-order was twisted. 我不知道为什么z顺序会扭曲。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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