繁体   English   中英

GridView空引用异常C#

[英]Gridview null reference exception c#

我通过以下代码在按钮单击事件的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());
            }

这给了我以下错误:

Sales System1.exe中发生了类型为'System.NullReferenceException'的未处理异常

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

如果不这样做,则将代码数据添加到gridview中。 但是当我放这段代码时,它给出了以上错误。 我需要做什么?

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;
    }
}

由于将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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM