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