2017-04-06 120 views
1

我以爲我已經完成了我的研究並計算出來了,但是當我試圖將數據從一種表單傳遞到另一種表單時,程序會拋出異常。我使用委託來嘗試以另一種形式調用函數。這是我的代碼。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爲空

我覺得我很想念一件簡單的事情。任何關於如何使這項工作的建議?

+1

你確定'GotoRecord爲null'是否是實際的異常信息?這不是一個標準的消息... – DavidG

+1

它看起來好像沒有訂閱者在這個活動上迷上了。微軟規定了一種調用事件處理程序的標準方式。雖然C#6有更好的解決方法。只是谷歌乾淨的事件處理程序調用 - 約翰Skeet有一個很好的文章。 –

+0

如果對'frmDataView.GetInstance()'的調用在Visible屬性設置爲true的情況下返回,則最初將不會分配GotoRecord事件(並且將爲空) – David

回答

2

尤金建議:

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

,或者如果在舊版本,而不是使用其他線程:

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

編輯:呼叫更正錯誤。

+1

我嘗試了你的建議,並感到沮喪,因爲它不工作。特洛伊的建議中有一個錯誤,但那不是我的問題。對於任何人在未來看這個答案,語法應該是: 'GotoRecord?.Invoke(Current.data.IndexOf(sr))' 但是,根我的問題是,我有調用開放孩子的形式,我正在與錯誤的工作。我對此感到有點愚蠢,但我學會了一種更好的方式來處理事件處理程序,所以它解決了。謝謝 – Prdufresne