C#委托抛出异常

时间:2017-04-06 17:33:21

标签: c# winforms delegates

我以为我已经完成了我的研究并想出了这个,但是当我尝试将数据从一个表单传递到另一个表单时,程序会抛出异常。我使用委托来尝试从另一个表单中调用一个函数。这是我的代码。

在父母表格中:

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为空

我觉得我错过了一些简单的事情。关于如何使这个工作的任何建议?

1 个答案:

答案 0 :(得分:2)

正如欧仁所说:

GotoRecord?.Invoke(Current.data.IndexOf(sr));

或者如果是旧版本而不使用其他线程:

if (GotoRecord != null)
{
    GotoRecord(Current.data.IndexOf(sr));
}

编辑:纠正了通话中的错误。