【发布时间】:2014-12-26 13:54:19
【问题描述】:
在我的表单上,我有一个名为“panelShowList”的 Panel 容器。
在我的项目中,我添加了一个新类,如下所示:
class myNewClass
{
private int newPanelPos = 30;
private const int spaceBetweenElements = 30;
private const int panelWidth = 90;
private const int panelHeight = 40;
private int elementPos = 0;
private ArrayList myPanels = new ArrayList() { };
// some irelevant methods
public void addElementPanels(Panel dataPanel, Panel nextPanel)
{
myPanels.Add(dataPanel);
myPanels.Add(nextPanel);
}
public void displayPanels()
{
foreach (Panel tmp in myPanels)
{
// here i'm stuck
// i need to do something like this :
// myMainForm.panelShowList.Controls.Add(tmp);
// of course this is wrong! but i need a method to acces that control
}
}
}
基本上,我需要一种方法将 ArrayList 中的所有面板添加到表单中的“panelShowList”控件上。
我尝试过这样的事情:
public void displayPanels()
{
frmMain f = new frmMain();
foreach (Panel tmp in myPanels)
{
f.display(tmp);
// where display(Panel tmp) is a function in my Form, who access
// "panelShowList" control and add a new Panel
}
}
但只有当我这样做时它才有效:
f.ShowDialog();
另一个表格打开了。
任何建议将不胜感激。
【问题讨论】:
-
表单只有在打开时才存在。所以不开放的时候不访问是正常的。要修复它,您需要创建一个静态对象并将表单存储在其中。所以你可以在它关闭时访问它。
-
@vgSefa:本质上是使用静态值作为全局变量,这是一种非常糟糕的使用模式。保持值的范围比将它们转储到某个地方让所有人看到要好。此外,您的第一个陈述(“表单仅在打开时才存在”)显然是错误的。与任何对象一样,表单对象只要在范围内就存在。
-
请不要使用
ArrayList。在这种情况下最好使用通用列表:private IList<Panel> myPanels = new List<Panel>(); -
@khlr 非常感谢您的建议。我对 C# 没有任何经验,所以我还在学习很多东西。
标签: c#