var panel = new Panel()
{
AutoSize = true,
Height = 45,
BackColor = Color.WhiteSmoke,
Name = "pnlTaskAssignation"
};
创建后,我想以以下方式访问该面板的控件:
foreach(Control c in pnlTaskAssignation.Controls)
{
if(c is ComboBox)
{
countLabels++;
}
}
问题是我以动态方式创建了Pannel,因此在代码中我无法引用它。因此pnlTaskAssignation
不存在。.如果是动态创建的,该如何访问面板控件?
答案 0 :(得分:1)
只需保留对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++;
}
}