繁体   English   中英

在winform c#.net应用程序中更改动态添加的控件的值,如何跟踪动态添加的控件

[英]Change values of dynamically added controls in winform c#.net application, how to track dynamically added controls

我在 tableLayoutpanel 的行内动态添加了控件,添加的控件是标签、链接标签和图片框。

现在,我想通过单击按钮将这些动态添加的控件(标签、链接标签)的值(文本属性)更改为某个指定值。

我该怎么做呢? 请帮忙写代码。

这些动态控件是否有某种 ID,就像我们在 HTML 中一样。

另外,我想用这个,但都是徒劳的............

Control[] GettableLayoutPanelControls = new Control[11];

          GettableLayoutPanelControls =  tableLayoutPanel1.Controls.Find("Control Name", true) ;

             GettableLayoutPanelControls.SetValue("CHANGED VALUE ", 0); //this line gives error..........

尝试这样的事情,它将添加 11 个新文本框(或您想要的任何其他控件):

int NumberOfTextBoxes = 11;
TextBox[] DynamicTextBoxes = new TextBox[NumberOfTextBoxes];
int ndx = 0;

while (ndx < NumberOfTextBoxes) 
{
    DynamicTextBoxes[ndx] = new TextBox();
    DynamicTextBoxes[ndx].Name = "TextBox" + ndx.ToString();
    // You can set TextBox value here:
    // DynamicTextBoxes[ndx].Text = "My Value";
    tableLayoutPanel1.Controls.Add(DynamicTextBoxes[ndx]);
    ndx++;
}

这将动态地将文本框添加到您的 TableLayout 控件。 如果您以后需要检索它们:

foreach (Control c in TableLayoutPanel1.Controls)
{
    if (c is TextBox)
    {
        TextBox TextBoxControl = (TextBox)c;

        // This will modify the value of the 3rd text box we added
        if (TextBoxControl.Name.Equals("TextBox3"))      
            TextBoxControl.Text = "My Value";
    }
}

最直接的方法是在私有字段中跟踪动态创建的控件。

private Label _myLabel;
_myLabel = new Label();
myLabel.Text = "Hello World!";
tableLayoutPanel1.Controls.Add(myLabel);
// ... later in the button click handler ... //
myLabel.Text = "Goodbye Cruel World!";

请记住,Windows Forms 是一个有状态的环境,与 ASP.NET 不同,因此当用户与表单交互时,字段不会丢失其值。

预计到达时间:

Label dynamic_label = new Label();
for(in i =0;i<6;i++){this.Controls.Add(dynamic_label);}

您评论中的此代码添加了 SAME label 5 次。 我不认为这是你的意图。 当您设置 Text 属性时,它们都将具有相同的文本,因为它们引用了相同的控件。 您可以使用我的解决方案并声明

Label myLabel1, myLabel2, ..., myLabel5;

如果你有这么多,你要在一个循环中声明它们,那么我会将它们存储在Dictionary<string, Label>中,这样你就不必搜索数组来找到正确的数组。

暂无
暂无

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

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