在winform c#.net应用程序中更改动态添加控件的值,如何跟踪动态添加的控件
本文关键字:控件 动态 添加 何跟踪 跟踪 winform net 应用程序 | 更新日期: 2023-09-27 18:00:32
我在运行时在tableLayoutpanel的行中动态添加了控件,添加的控件是LABELS、LINKLABEL和PICTURE BOX。
现在,我想通过单击按钮将这些动态添加的控件(标签、链接标签)的值(文本属性)更改为某个指定值。
我该怎么做?请帮助编写代码。
这些动态控件是否有某种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窗体是一个有状态的环境,与ASP不同。NET,这样当用户与表单交互时,字段就不会丢失它们的值。
ETA:
Label dynamic_label = new Label();
for(in i =0;i<6;i++){this.Controls.Add(dynamic_label);}
您的注释中的这段代码添加了5次SAME标签。我不认为这是你的意图。当您设置Text属性时,它们都将具有相同的文本,因为它们引用了相同的控件。你可以使用我的解决方案并申报
Label myLabel1, myLabel2, ..., myLabel5;
如果有太多,以至于在循环中声明它们,那么我会将它们存储在Dictionary<string, Label>
中,这样就不必搜索数组来找到正确的数组。