我以为我已经完成了我的研究并计算出来了,但是当我试图将数据从一种表单传递到另一种表单时,程序会抛出异常。我使用委托来尝试以另一种形式调用函数。这是我的代码。C#委托抛出异常
在父窗体:
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为null'是否是实际的异常信息?这不是一个标准的消息... – DavidG
它看起来好像没有订阅者在这个活动上迷上了。微软规定了一种调用事件处理程序的标准方式。虽然C#6有更好的解决方法。只是谷歌干净的事件处理程序调用 - 约翰Skeet有一个很好的文章。 –
如果对'frmDataView.GetInstance()'的调用在Visible属性设置为true的情况下返回,则最初将不会分配GotoRecord事件(并且将为空) – David