动态创建面板的访问控制

时间:2019-05-06 18:32:55

标签: c# winforms

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不存在。.如果是动态创建的,该如何访问面板控件?

1 个答案:

答案 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++;
    }
}