Reputation: 7025
I'm building an application that have a DataGridView and sometimes during the program execution I need to update a value from a specific row and column, because this value contains data related with the quantity of some item.
So to exemplify imagine you have this DataGridView:
0 1
+----------+----------+
| Item | Quantity |
+----------+----------+
0 | Candy L | 1 |
+----------+----------+
And I need to add +1 to the row 0 and column 1. So I'd have this as result.
0 1
+----------+----------+
| Item | Quantity |
+----------+----------+
0 | Candy L | 2 |
+----------+----------+
I already did some stuff:
int rowIndex = 0;
foreach (DataGridViewRow dgvRow in dataGridViewLista.Rows)
{
if (dgvRow.Cells[0].FormattedValue.ToString() == "Candy")
// Here I'd update the row (at this point I already have the row index)
rowIndex++;
}
Thanks.
Upvotes: 3
Views: 11710
Reputation: 8656
You could use somtehing like this:
int rowIndex = 0;
foreach (DataGridViewRow dgvRow in dataGridViewLista.Rows)
{
if (dgvRow.Cells[0].FormattedValue.ToString() == "Candy")
{
int value;
if(int.TryParse(dgvRow.Cells[1].FormattedValue, out value))
dgvRow.Cells[1].Value = value + 1;
}
rowIndex++;
}
Upvotes: 0
Reputation: 223392
You need to get the Quantity cell's value, parse it to integer or respective type and then add 1
to it assign the result back to Cell.Value
property like:
if (dgvRow.Cells[0].FormattedValue.ToString() == "Candy")
{
int qty = Convert.ToInt32(dgvRow.Cells[1].FormattedValue);
qty += 1;
dgvRow[0].Cells[1].Value = qty;
}
Its better if you parse using int.TryParse method to avoid exceptions
Upvotes: 7