【问题标题】:Gridview null reference exception c#Gridview空引用异常c#
【发布时间】:2017-04-06 05:22:28
【问题描述】:

我正在通过以下代码在按钮单击事件的 gridview 中添加数据:

            int row = 0;
            dataGridView1.Rows.Add();
            row = dataGridView1.Rows.Count - 2;
            dataGridView1["Description",row].Value = name;
            dataGridView1["Quantity", row].Value = qty.Text;
            dataGridView1["Price", row].Value = p;
            dataGridView1["Discountcell", row].Value = "0000";
            dataGridView1["amt", row].Value = tot;

它工作得很好。 现在我想当我在 输入折扣时,折扣应该从总金额中减去。为此,我有以下代码:

foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                int n = item.Index;
               dataGridView1["amt", n].Value = tot - float.Parse(dataGridView1.Rows[n].Cells[3].Value.ToString());
            }

这里它给了我以下错误:

未处理的类型异常 销售 System1.exe 中发生“System.NullReferenceException”

附加信息:对象引用未设置为 对象。

在 gridview 中添加没有此减法代码的数据。但是当我输入这段代码时,它给出了上述错误。我需要做什么?

【问题讨论】:

  • 什么是tot??它是在某个地方定义的吗?
  • tot 是我从价格乘以数量得到的金额
  • 对单元格值进行空检查或使用 TryParse。
  • 你能在抛出这个异常的地方检查哪个元素为空
  • @ReadyFreddy 如何查看告诉我?

标签: c# gridview


【解决方案1】:

由于您将AllowUserToAddRows 设置为true,因此dataGridView1.Rows 在行列表中包含编辑器行。

事实上,foreach 循环中分配给item 变量的最后一个值正是该行(编辑器行)。如果您不想将AllowUserToAddRows 设置为false,您可以使用行本身的IsNewRow 属性跳过处理该行。

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (item.IsNewRow) break;
    dataGridView1["amt", item.Index].Value = tot - float.Parse(item.Cells["Discountcell"].Value.ToString());
}

【讨论】:

    【解决方案2】:
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
        float f;
        int n = item.Index;
        if (float.TryParse(dataGridView1.Rows[n].Cells[3].Value.ToString(), out f))
        {
             dataGridView1["amt", n].Value = tot - f;
        }
    }
    

    【讨论】:

    • 先生错误是因为它还在下一行还没有添加,因为启用了编辑。现在请告诉我我做了哪些没有这个错误
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 2023-03-15
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多