首页 > 解决方案 > 动态创建的面板的访问控制

问题描述

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

标签: c#winforms

解决方案


只需保留对 的原始引用即可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++;
    }
}

推荐阅读