为什么在为DataGridView行单元格赋值时获取空引用异常[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我已经访问过StackOverflow上的this问题,但我没有得到任何解决方案。

在我的Windows窗体应用程序中,我添加了一个功能,允许用户双击DataGridView中的行,并且该特定行的值显示在子窗体的文本框中。用户现在可以编辑这些值,即可以编辑数量等。

现在,我想将此值(编辑的数量)分配回同一DataGridView的当前行的特定单元格。我将这些值从子窗体返回到我的主窗体上,但是当我在公共方法中将此编辑的数量值重新分配给DataGridView时,因此我在DataGridView上获得了一个Null的Reference Exception。

这是我的代码,我得到NulledReferenceException。

//A public method to which I have passed the customQuantity from my child form
public void GetSoldItemQuantity(string customQuantity)
{
    //assign this customQuantity to an int variable
    int globalQuantity = Convert.ToInt32(customQuantity);
    if (globalQuantity > 1)
    {
     //dgvAllSoldItems is the DataGridView from where I have passed 
     //the currentRow data to the child form. At this stage,
     //I have the updated value returned from my child form and is
     //currently stored in the globalQuantity variable but I cannot assign it
     //back to the grid.

        dgvAllSoldItems.CurrentRow.Cells[1].Value = globalQuantity;

    }
}

这是我的子表单上的按钮代码,它将自定义数量值传递给父表单上的上述公共方法。

private void btnProceedWithNewItemQuantity_Click(object sender, EventArgs e)
{
    string newItemQuantity = txtChooseSaleQuantity.Text.Trim();

    frmNewSale parentSale = this.Parent as frmNewSale();//now I am getting error the null reference exception on this line in debugger.
    parentSale.GetSoldItemQuantity(newItemQuantity);

    this.Close();
}

虽然我在子窗体上的按钮单击事件上创建了父类的新实例,但这不是正确的方法。所以,我使用this.Parent代替,但现在我在这一行得到了同样的例外。

c# winforms nullreferenceexception
1个回答
-1
投票

您看到错误的原因是您没有在函数dvgAllSoldItems中定义GetSoldItemQuantity或不可见。

因为我不确定你的函数GetSoldItemQuantity的上下文。我可以想到一个解决方案,你可以参考你的GridView对象。那就是将GridView对象传递给下面的函数:

GetSoldItemQuantity(string customQuantity,  DataGridView dgvAllSoldItems)

或者如果您有一个填充表单的视图模型,您可以返回customQuantity值并将其作为新的数量值分配给模型。

如果dvgAllSoldItems是一个全局变量(或者在与GetSoldItemQuantity函数相同的类中找到),那么您可以使用this.dvgAllSoldItems来引用全局定义的对象。

© www.soinside.com 2019 - 2024. All rights reserved.