如何更新DataGridView中特定行和列的值?

Zig*_*gnd 3 c# datagridview

我正在构建一个具有DataGridView的应用程序,有时在程序执行期间我需要更新特定行和列的值,因为此值包含与某个项目的数量相关的数据.

所以为了举例说明你有这个DataGridView:

       0          1
  +----------+----------+
  |   Item   | Quantity |
  +----------+----------+
0 | Candy L  |    1     |
  +----------+----------+
Run Code Online (Sandbox Code Playgroud)

我需要在第0行和第1列添加+1.所以我得到了这个结果.

       0          1
  +----------+----------+
  |   Item   | Quantity |
  +----------+----------+
0 | Candy L  |    2     |
  +----------+----------+
Run Code Online (Sandbox Code Playgroud)

我已经做了一些事情:

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++;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Hab*_*bib 7

您需要获取Quantity单元格的值,将其解析为整数或相应类型,然后添加1到它将结果分配回Cell.Value属性,如:

if (dgvRow.Cells[0].FormattedValue.ToString() == "Candy")
{
 int qty = Convert.ToInt32(dgvRow.Cells[1].FormattedValue);
 qty += 1;
 dgvRow[0].Cells[1].Value = qty;
}
Run Code Online (Sandbox Code Playgroud)

如果使用int.TryParse方法解析以避免异常,则更好