首页 > 解决方案 > C# DataGridView 单元格更新不更新最后一行

问题描述

我有一个按钮,它使用组合框中选择的任何内容更新第 3 (C) 列(标题除外)中的所有值。

    private void updateExcel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount - 1; i++)
        {
            if (!RowIsEmpty(i))
            {
                dataGridView1[2, i].Value = Combo.Text;
            }
        }
    }

除了不更新最后一行之外,这还有效。

RowIsEmpty:

    private bool RowIsEmpty(int rowIndex)
    {
        for (int i = 0; i < dataGridView1.ColumnCount; i++)
        {
            if (dataGridView1.Rows[rowIndex].Cells[i].Value != null &&
                dataGridView1.Rows[rowIndex].Cells[i].Value.ToString() != "")
            {
                return false;
            }
        }
        return true;
    }

标签: c#winformsdatagridview

解决方案


我认为你的问题出在updateExcel_Click..

在我看来,问题在于:

for (int i = 0; i < dataGridView1.RowCount - 1; i++)

因为您在这里跳行,所以假设dataGridView1.RowCount值为 3,而您正在dataGridView1.RowCount - 1这样做dataGridView1.RowCount = 2

有了这个,你的意志会运行 0、1 和 2。当目标时,在我看来,你想让他运行 0、1、2 和 3。

你在你的问题上说的问题是:不更新最后一行,因为 for 正在跳过最后一行..

解决方案:

private void updateExcel_Click(object sender, EventArgs e)
{
   for (int i = 0; i < dataGridView1.RowCount; i++)
   {
      if (!RowIsEmpty(i))
      {
          dataGridView1[2, i].Value = Combo.Text;
      }
   }
}

或者,如果您想保留已有的逻辑,则需要在 for 中添加 this <,如下所示:

for (int i = 0; i <= dataGridView1.RowCount - 1; i++)

推荐阅读