【问题标题】:System.NullReferenceException when no DataGridViewRow was selected [duplicate]未选择 DataGridViewRow 时出现 System.NullReferenceException [重复]
【发布时间】:2018-06-24 11:20:56
【问题描述】:

我的窗口表单中有两个 dataGridView,每个 gridview 按钮用于编辑单元格的内容。但是,当我启动我的应用程序时,当我没有先单击视图中的一行时,我总是会收到 System.NullReferenceException

在我启动应用程序后,该行被选中并呈蓝色: selected row

我在加载方法中设置了以下内容:

            dataGridView1.Rows[0].Selected = true;
            dataGridView2.Rows[0].Selected = true;

第二个 DatagridView 工作正常。不知道为什么……

这是我的一键代码:

private void button2_Click(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count > 0)
        {
            int _selectedArticle_ID, _selectedArticle_ArtNr;
            string _selectedArticle_Artikel, _selectedArticle_Barcode;
            decimal _selectedArticle_einkaufsPreis, _selectedArticle_verkaufsPreis;

            _selectedArticle_ID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value);
            _selectedArticle_ArtNr = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value);
            _selectedArticle_Artikel = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value.ToString();
            _selectedArticle_einkaufsPreis = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[3].Value);
            _selectedArticle_verkaufsPreis = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[4].Value);
            _selectedArticle_Barcode = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[5].Value.ToString();

            f3 = new Form3(); // (_selectedArticle_ID, _selectedArticle_Anz, _selectedArticle_ArtNr, _selectedArticle_Artikel, _selectedArticle_Preis, _selectedArticle_Barcode, this);
            f3.Show();
        }
    }

【问题讨论】:

  • 答案是你的问题,System.NullReferenceException when no DataGridViewRow was selected。当没有选择 DataGridViewRow 并且您正在检查 if (dataGridView1.SelectedRows.Count > 0)
  • 当我开始我的应用程序时,第一行被选中..该行是蓝色的..
  • 防御性代码:不要总是假设你的对象会有价值。将您的 if 条件更改为 if (dataGridView1 != null && dataGridView1.SelectedRows.Count > 0)
  • 哪一行抛出异常?
  • 当您得到异常时,使用调试器检查该行的元素以查看哪个部分为空。

标签: c# forms winforms datagridview datagrid


【解决方案1】:

没有用于检查所选行的数据网格。因此,由于 null 值,此行会引发错误: if (dataGridView1.SelectedRows.Count > 0)

您可以输入if (dataGridView1 == null) { return; } 之类的内容来先检查,如果 dataGridView1 仍然为空,则退出该方法。

【讨论】:

  • 但在我启动应用程序后该行被选中并显示为蓝色
  • 嗯。发布的方法似乎仅适用于 dataGridView1。 dataGridView2 有单独的按钮单击方法吗?如果有,方法有什么不同吗?
  • 对于 datagridview2 是一个额外的按钮,但它的代码完全相同.. 该行是蓝色的并被选中.. 我单击按钮弹出窗体 3.. 不适用于 datagridview1
  • dataGridViews 是如何被填充的? dataGridView1和dataGridView2的内容有区别吗?如果是这样,当它们的内容相同时是否会发生错误?我想这些将是我接下来要检查的事情。
  • 其中的内容不同,但是..方法完全相同...我认为这是因为第二个gridview处于焦点或其他什么..
猜你喜欢
  • 1970-01-01
  • 2018-07-05
  • 2013-01-23
  • 2023-03-25
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多