【发布时间】:2017-04-06 17:33:20
【问题描述】:
我以为我已经完成了研究并弄清楚了这一点,但是当我尝试将数据从一种形式传递到另一种形式时,程序会抛出异常。我正在使用委托尝试以一种形式从另一种形式调用函数。这是我的代码。
在父窗体中:
private void viewListToolStripMenuItem_Click(object sender, EventArgs e)
{
frmDataView dataview = frmDataView.GetInstance();
if (dataview.Visible)
dataview.BringToFront();
else
{
dataview.GotoRecord += GotoRecord;
dataview.Show();
}
}
private void GotoRecord(int index)
{
Current.record = index;
loadRecord(index);
setNavButtons();
}
在子窗体中,我尝试使用以下代码在父窗体中调用 GotoRecord:
public partial class frmDataView : Form
{
AdvancedList<ScoutingRecord> displayedData = new AdvancedList<ScoutingRecord>(Current.data);
// Set the form up so that only one instance will be available at a time.
private static frmDataView _instance;
public static frmDataView GetInstance()
{
if (_instance == null)
_instance = new frmDataView();
return _instance;
}
public delegate void GotoRecordHandler(int index);
public GotoRecordHandler GotoRecord;
private void dgvMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int teamnumber = (int)dgvMain.Rows[row].Cells["TeamNumber"].Value;
int matchnumber = (int)dgvMain.Rows[row].Cells["MatchNumber"].Value;
ScoutingRecord sr = Current.data.FirstOrDefault(x => x.TeamNumber == teamnumber && x.MatchNumber == matchnumber);
//int index = Current.data.IndexOf(sr);
GotoRecord(Current.data.IndexOf(sr));
}
每当我运行代码时,它都会抛出以下异常:
GotoRecord 为空
我觉得我错过了一些简单的东西。有关如何使其正常工作的任何建议?
【问题讨论】:
-
您确定
GotoRecord was null是实际的异常消息吗?这不是标准信息... -
看起来好像没有订阅者迷上该事件。 Microsoft 规定了调用事件处理程序的标准方法。不过,C# 6 有更好的解决方法。 Just google Clean Event Handler Invocation - John Skeet 有一篇很好的文章。
-
如果对
frmDataView.GetInstance()的调用返回并将 Visible 属性设置为 true,则最初将永远不会分配 GotoRecord 事件(并且将为 null) -
DavidG,我剪切并粘贴了异常消息。今晚会看看其他建议。谢谢。