【发布时间】:2019-07-24 20:38:48
【问题描述】:
我已经访问过 StackOverflow 上的 this 问题,但我的问题没有得到任何解决方案。
在我的 Windows 窗体应用程序中,我包含了一项功能,该功能允许用户双击 DataGridView 中的一行,并且该特定行的值显示在子窗体的文本框中。用户现在可以编辑这些值,即可以编辑数量等。
现在,我想将此值(编辑的数量)分配回同一 DataGridView 的当前行的特定单元格。我将子表单中的这些值返回到我的主表单上,但是由于我正在以公共方法将这个编辑的数量值重新分配给 DataGridView,所以我在 DataGridView 上得到了一个空引用异常。
这是我得到 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,但现在我在这条线上遇到了同样的异常。
【问题讨论】:
-
@RandRandom 我在顶部提到了同样的问题。它没有帮助我!
-
请@Noor 重复解释几乎所有可能的情况。您只需要启动调试器,在函数的第一行放置一个断点,按 f10 并检查哪个变量为空。然后开始调查为什么该变量为空。很简单
-
注意到了,但它仍然是 NRE 的副本 - 抱歉,但您甚至没有提到引发异常的行上的 null 内容 - 在我看来,您缺乏阅读知识一个错误。那么
dgvAllSoldItems.CurrentRow.Cells[1].Value那条线上的空值是dgvAllSoldItems吗?是CurrentRow吗?Cells是[1]返回 null 吗? - 首先弄清楚什么是空的,然后想想为什么它会在你的情况下 -
现在试着理解为什么
DataGrid的CurrentRow可能为空 - 这是一个很好的起点docs.microsoft.com/en-us/dotnet/api/… -The DataGridViewRow that represents the row containing the current cell, or null if there is no current cell.也许你更喜欢SelectedRows- @987654323 @ -
我很困惑 - 你现在是说
GetSoldItemQuantity方法无关紧要吗?你在调试器中看到了什么?this.Parent?的价值是多少老实说,您发布的代码 -this.Parent as frmNewSale()- 甚至无法编译 - 所以我对此表示怀疑......
标签: c# winforms nullreferenceexception