0

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

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

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

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

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

Control[] GettableLayoutPanelControls = new Control[11];

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

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

2 回答 2

3

尝试这样的事情,它将添加 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";
    }
}
于 2011-06-28T18:15:24.023 回答
0

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

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

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

预计到达时间:

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

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

Label myLabel1, myLabel2, ..., myLabel5;

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

于 2011-06-28T18:13:39.300 回答