如果您要拥有一个静态控件,至少要为其提供一个包装器,以便您可以捕获和处理您的问题。
考虑将您的代码修改为如下所示。一旦你解决了你的错误,你就可以消除任何你不需要的东西。
private static DataGrid dataGrid;
private static myForm myInstance;
public myForm()
{
InitializeComponent();
myInstance = this; // set 'myInstance' before DataGrid1 stuff
DataGrid1.Height = 524;
DataGrid1.Width = 468;
DataGrid1.CurrentCellChanged += new EventHandler(dataGrid_CurrentCellChanged);
}
public static DataGrid DataGrid1 {
get {
try {
if ((myInstance == null) || myInstance.IsDisposed) {
throw new Exception("myForm is already disposed. No controls available.");
}
if ((dataGrid == null) || dataGrid.IsDisposed) {
dataGrid = new DataGrid();
dataGrid.Location = pt;
dataGrid.Font.Name = "Tahoma";
dataGrid.Font.Size = 9;
dataGrid.BackgroundColor = Color.Azure;
dataGrid.GridLineColor = Color.Black;
dataGrid.ColumnHeadersVisible = false;
dataGrid.RowHeadersVisible = false;
dataGrid.PreferredRowHeight = 60;
this.Controls.Add(dataGrid);
}
} catch (Exception err) {
Console.WriteLine(err); // put a breakpoint HERE
}
return dataGrid;
}
set {
try {
if ((myInstance == null) || myInstance.IsDisposed) {
throw new Exception("myForm is already disposed. No controls available.");
}
if ((dataGrid == null) || dataGrid.IsDisposed) {
dataGrid = new DataGrid();
dataGrid.Location = pt;
dataGrid.Font.Name = "Tahoma";
dataGrid.Font.Size = 9;
dataGrid.BackgroundColor = Color.Azure;
dataGrid.GridLineColor = Color.Black;
dataGrid.ColumnHeadersVisible = false;
dataGrid.RowHeadersVisible = false;
dataGrid.PreferredRowHeight = 60;
this.Controls.Add(dataGrid);
}
} catch (Exception err) {
Console.WriteLine(err); // put a breakpoint HERE
}
dataGrid = value;
}
}
最后,确保您的dataGrid_CurrentCellChanged
事件处理程序(以及程序中的所有其他内容)引用这个公共DataGrid1
对象,而不是dataGrid
- 否则您会发现自己再次遇到同样的错误。