Prdufresne
Prdufresne

Reputation: 296

C# delegate throwing an exception

I thought I had done my research and figured this out, but when I try to pass data from one form to another, the program throws an exception. I'm using a delegate to try to call a function in one form from another. Here's the code I have.

In the parent form:

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();
}

In the child form, I'm trying to call GotoRecord in the parent form with the following code:

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));
    }

Whenever I run the code, it throws the following exception:

GotoRecord was null

I feel like I'm missing something simple. Any suggestions on how to get this working?

Upvotes: 1

Views: 514

Answers (1)

Troy Mac1ure
Troy Mac1ure

Reputation: 647

As Eugène suggested:

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

or if on an older version and not using other threads:

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

EDIT: Corrected mistake in call.

Upvotes: 2

Related Questions