[英]iterating over a DataGridView in C# - Object reference not set to an instance of an object
I have the following code: 我有以下代码:
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if (r.Cells["Product"].Value.ToString() == p.Title)
{
tally += p.Price;
}
}
);
}
At the if statement on run time, I am getting the error
: 在运行时的if语句中,
error
:
An unhandled exception of type 'System.NullReferenceException'
occurred in WindowsFormsApplication1.exe
Additional information: Object reference not set to an instance of an object.
What might be the problem ? 可能是什么问题?
Any thought where i went wrong? 有没有想到我错了?
do it like this 像这样做
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if (!string.isNullorWhiteSpace(Convert.ToString(r.Cells["Product"].Value)) && Convert.ToString(r.Cells["Product"].Value).Equals(p.Title,StringComparison.OrdinalIgnoreCase))
{
tally += p.Price;
}
}
);
}
Do you have a column with "Product" exactly? 您是否有“产品”一栏? Can you try index instead?
您可以改用索引吗?
r.Cells[1].Value
something like that? 这样的东西?
Also, you might have to convert it into a particular cell type? 另外,您可能必须将其转换为特定的单元格类型? Ex: if its a textboxcell then you might have to do
例如:如果它是一个textboxcell,那么您可能需要做
r.Cells[1].Text
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if(r.Cells["Product"]!=null)
{
if(r.Cells["Product"].Value!=null)
{
if (r.Cells["Product"].Value.ToString() == p.Title)
{
tally += p.Price;
}
}
}
}
);
}
需要检查cell.Value是否为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.