【问题标题】:C# delegate throwing an exceptionC#委托抛出异常
【发布时间】:2017-04-06 17:33:20
【问题描述】:

我以为我已经完成了研究并弄清楚了这一点,但是当我尝试将数据从一种形式传递到另一种形式时,程序会抛出异常。我正在使用委托尝试以一种形式从另一种形式调用函数。这是我的代码。

在父窗体中:

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 was null 是实际的异常消息吗?这不是标准信息...
  • 看起来好像没有订阅者迷上该事件。 Microsoft 规定了调用事件处理程序的标准方法。不过,C# 6 有更好的解决方法。 Just google Clean Event Handler Invocation - John Skeet 有一篇很好的文章。
  • 如果对 frmDataView.GetInstance() 的调用返回并将 Visible 属性设置为 true,则最初将永远不会分配 GotoRecord 事件(并且将为 null)
  • DavidG,我剪切并粘贴了异常消息。今晚会看看其他建议。谢谢。

标签: c# winforms delegates


【解决方案1】:

正如欧仁建议的那样:

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

或者如果在旧版本上并且不使用其他线程:

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

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

【讨论】:

  • 我尝试了您的建议,但也很沮丧,因为它也不起作用。建议特洛伊有一个错误,但这不是我的问题。对于任何在未来查看此答案的人,语法应该是:'GotoRecord?.Invoke(Current.data.IndexOf(sr))' 但是,我的问题的根源是我有重复的函数来调用打开子表单,我和错误的人一起工作。我对此感到有点愚蠢,但我学会了一种更好的方式来使用事件处理程序,所以它成功了。谢谢
猜你喜欢
  • 2021-10-30
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多