winform c#.net应用程序中动态添加控件的更改值,如何跟踪动态添加的控件
我在运行时在 tableLayoutpanel 的行内动态添加了控件,添加的控件是标签、LINKLABEL 和图片框。
现在,我想通过单击按钮将这些动态添加的控件(标签、链接标签)的值(文本属性)更改为某个指定值。
我该怎么做?请帮忙写代码。
这些动态控件是否有某种 ID,就像我们在 HTML 中那样。
另外,我正在尝试使用这个,但一切都是徒劳的............
Control[] GettableLayoutPanelControls = new Control[11];
GettableLayoutPanelControls = tableLayoutPanel1.Controls.Find("Control Name", true) ;
GettableLayoutPanelControls.SetValue("CHANGED VALUE ", 0); //this line gives error..........
I have added controls dynamically on runtime inside the rows of a tableLayoutpanel , the controls added are LABELS, LINKLABEL AND A PICTURE BOX.
Now , i want to change the value(Text Property) of these dynamically added controls(Labels, Linklabels) to some specified value, on a button click.
How do i do this? Please help with code.
Is there some kind of ID for these dynamically controls like we have in HTML.
Also , am trying to use this but all in vain...........
Control[] GettableLayoutPanelControls = new Control[11];
GettableLayoutPanelControls = tableLayoutPanel1.Controls.Find("Control Name", true) ;
GettableLayoutPanelControls.SetValue("CHANGED VALUE ", 0); //this line gives error..........
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这样的操作,这将添加 11 个新文本框(或您想要的任何其他控件):
这将动态地将文本框添加到您的 TableLayout 控件中。如果您稍后需要检索它们:
Try something like this, which will add 11 new text boxes (or any other control you want):
This will dynamically add Text Boxes to your TableLayout control. If you need to retreive them later:
最直接的方法是在私有字段中跟踪动态创建的控件。
请记住,Windows 窗体是一个有状态的环境,与 ASP.NET 不同,因此当用户与窗体交互时字段不会丢失其值。
ETA:
您评论中的这段代码添加了相同的标签 5 次。我不认为那是你的意图。当您设置 Text 属性时,它们都将具有相同的文本,因为它们引用相同的控件。您可以使用我的解决方案并声明
如果您有太多要在循环中声明它们,那么我会将它们存储在
Dictionary
中,这样您就不必搜索数组以找到正确的数组。The most straightforward way to do this is to keep track of the dynamically created controls in a private field.
Remember, Windows Forms is a stateful environment, unlike ASP.NET, so fields don't lose their values when the user interacts with the form.
ETA:
This code from your comment adds the SAME label 5 times. I don't think that's your intent. When you set the Text property they will all have the same text because they reference the same control. You can use my solution and declare
If you have so many that you're declaring them in a loop then I would store them in a
Dictionary<string, Label>
so that you don't have to search the array to find the correct one.