c# - 动态创建的面板的访问控制
问题描述
var panel = new Panel()
{
AutoSize = true,
Height = 45,
BackColor = Color.WhiteSmoke,
Name = "pnlTaskAssignation"
};
创建它后,我想访问该面板的控件,如下所示:
foreach(Control c in pnlTaskAssignation.Controls)
{
if(c is ComboBox)
{
countLabels++;
}
}
问题是我动态地创建了面板,所以在代码中我无法引用它。所以pnlTaskAssignation
不存在..如果我动态地创建面板控件,我该如何访问它?
解决方案
只需保留对 的原始引用即可panel
。如果您愿意,您可以pnlTaskAssignation
在类级别自己声明变量。
class MyForm
{
protected Panel pnlTaskAssignation; //Add this yourself
public void MyForm_Load(object sender, EventArgs e)
{
var panel = new Panel()
{
AutoSize = true,
Height = 45,
BackColor = Color.WhiteSmoke,
Name = "pnlTaskAssignation"
}
pnlTaskAssignation = panel; //Save the reference here
};
然后这段代码现在可以工作了:
foreach(Control c in pnlTaskAssignation.Controls) //References the member variable defined above
{
if (c is ComboBox)
{
countLabels++;
}
}
推荐阅读
- javascript - 如何在 VueJS 应用程序中自定义 CKEditor 5
- javascript - 有没有办法将泛型类型限制为仅在打字稿中的普通对象?
- android - 如何使用路径删除文件
- angular7 - 在 ionic 4 中使用 ion-tabs 时,内容滚动不起作用
- node.js - 为postgresQL续集bulkCreate updateOnDuplicate?
- linux - Shell递归地重命名很多文件
- spring-boot - Spring-Cloud-Streams Kafka - 如何阻止消费者
- flutter - 即使在 android studio 上运行 flutter clean 后,Flutter 也不会在设备上重新安装我的应用程序
- java - 从java中的json项目获取价值
- sql - 工作构建的定制自动售货机 SQL 帮助