Reputation: 35
I have a project and I am trying to sum up rows of the same ID together.
Like for example:
ID Quantity
1 5
1 7
2 10
2 18
1 8
So when I press a button, quantity under ID 1 will give me 20 and for ID 2, I will get 28. But I faced an error specifying that "Object reference is not set to an instance of an object". Below are my codes:
id = int.Parse(row.Cells[0].Value.ToString());
This is the code that shows the error msg:
int id = 0;
int qty = 0;
List<QuantityPerID> qtyList = new List<QuantityPerID>();
QuantityPerID qtyObj;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
id = int.Parse(row.Cells[0].Value.ToString());
qty = int.Parse(row.Cells[1].Value.ToString());
qtyObj = new QuantityPerID();
bool ifexists = false;
if (qtyList != null && qtyList.Count() > 0)
{
if (qtyList.Where(q => q.ID == id).Count() > 0)
{
ifexists = true;
}
}
if (ifexists)
{
qtyObj = qtyList.Where(q => q.ID == id).First();
qtyObj.Quantity += qty;
}
else
{
qtyObj.ID = id;
qtyObj.Quantity = qty;
qtyList.Add(qtyObj);
}
}
I would like to ask also is there any other easier method to achieve the same results?
Upvotes: 0
Views: 675
Reputation: 1629
Are you sure that Cells[0]
and Cells[1]
are not empty? You are calling the ToString on it's Values. Check if the Value is null before the call to ToString
if( null != row.Cells[0].Value )
{
id = int.Parse(row.Cells[0].Value.ToString());
}
if(null != row.Cells[1].Value)
{
qty = int.Parse(row.Cells[1].Value.ToString());
}
Do you see an empty line at the end of the rows? Does the DataGridView.AllowUserToAddRows property set to true?
If so, then this is the issue. You are also reading the values of the empty line.
Instead of the foreach, you can do it with a for loop
// notice the Count - 1.
for(var index = 0; index < dataGridView1.Rows.Count - 1; ++index)
{
// your code here
}
Upvotes: 1
Reputation: 536
Split this definition
id = int.Parse(row.Cells[0].Value.ToString());
into multiple parts to see what is generating your NullReferenceException (and possibly the Qty one too).
Or, at runtime, you could check the Cells' values using IntelliSense (if you hover above "Cells", or "row" it will show you their contents".
Upvotes: 0