3

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

因此,举例来说,假设您有这个 DataGridView:

       0          1
  +----------+----------+
  |   Item   | Quantity |
  +----------+----------+
0 | Candy L  |    1     |
  +----------+----------+

我需要将 +1 添加到第 0 行和第 1 列。所以我会得到这个结果。

       0          1
  +----------+----------+
  |   Item   | Quantity |
  +----------+----------+
0 | Candy L  |    2     |
  +----------+----------+

我已经做了一些事情:

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++;
}

谢谢。

4

2 回答 2

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;
}

如果您使用int.TryParse方法进行解析以避免异常,那就更好了

于 2013-04-30T12:00:56.050 回答
0

你可以像这样使用一些东西:

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++;
}
于 2013-04-30T12:04:20.960 回答