提问人:Noor 提问时间:3/3/2019 最后编辑:Jon SkeetNoor 更新时间:3/3/2019 访问量:362
为什么在将值分配给 DataGridView 行单元格时出现 Null 引用异常 [重复]
Why Getting Null Reference Exception On Assigning Value To DataGridView Row Cell [duplicate]
问:
我已经在 StackOverflow 上访问过这个问题,但我没有得到任何解决我的问题的方法。
在我的 Windows 窗体应用程序中,我包含了一项功能,该功能允许用户双击 DataGridView 中的一行,并且该特定行中的值显示在子窗体的文本框中。用户现在可以编辑这些值,即可以编辑数量等。
现在,我想将此值(编辑的数量)分配回同一 DataGridView 的当前行的特定单元格。我将子窗体中的这些值重新放在我的主窗体上,但是当我在公共方法中将此编辑的数量值重新分配给 DataGridView 时,因此我在 DataGridView 上获得了 Nulled 引用异常。
这是我的代码,我在其中获取 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();
}
尽管我在子窗体上的按钮单击事件上创建父类的新实例,但这不是正确的方法。所以,我用了这个。Parent 代替,但现在我在这一行上遇到了同样的异常。
答:
您看到错误的原因是您没有在函数中定义或不可见。dvgAllSoldItems
GetSoldItemQuantity
由于我不确定您的函数的上下文.我可以想出一个解决方案供您引用您的对象。即将对象传递给函数,如下所示:GetSoldItemQuantity
GridView
GridView
GetSoldItemQuantity(string customQuantity, DataGridView dgvAllSoldItems)
或者,如果视图模型填充了窗体,则可以返回该值并将其作为新的数量值分配给模型中。customQuantity
如果是全局变量(或与函数位于同一类中),则可以用于引用全局定义的对象。dvgAllSoldItems
GetSoldItemQuantity
this.dvgAllSoldItems
评论
dvgAllSoldItems
必须可见,代码才能编译、运行,然后给出异常。如果与在同一类中找到,则添加不执行任何操作(除非局部变量存在歧义,而局部变量不存在)。GetSoldItemQuantity
dvgAllSoldItems
GetSoldItemQuantity
this.
评论
dgvAllSoldItems.CurrentRow.Cells[1].Value
dgvAllSoldItems
CurrentRow
Cells
[1]
CurrentRow
DataGrid
The DataGridViewRow that represents the row containing the current cell, or null if there is no current cell.
SelectedRows
GetSoldItemQuantity
this.Parent?
this.Parent as frmNewSale()