简体   繁体   English

C#DataGridView单元格更新不更新最后一行

[英]C# DataGridView cell update not updating last row

I have a button which updates all values in column 3 (C) (except the header) with whatever has been selected in a combo box. 我有一个按钮,该按钮使用组合框中选择的内容更新第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;
            }
        }
    }

This works apart from it doesn't update the last row. 除了不更新最后一行外,这还行得通。

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

I think your problem is in the updateExcel_Click .. 我认为您的问题出在updateExcel_Click

The problem, in my point of view, is in this for: 我认为问题在于:

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

Because you are jumping rows here so, imagine dataGridView1.RowCount have a value of 3, and you are making dataGridView1.RowCount - 1 so dataGridView1.RowCount = 2 . 因为您要在此处跳过行,所以假设dataGridView1.RowCount的值为3,并且使dataGridView1.RowCount - 1 dataGridView1.RowCount = 2

With this your for will running 0, 1 and 2. When the objective, in my point of view, you wanna him to run 0, 1, 2 and 3. 这样,您的for将会运行0、1和2。在我看来,目标是您想要他运行0、1、2和3。

The problem you saying on your question is: Not updating last row, because for is jumping the last row.. 您在问题上说的问题是:不更新最后一行,因为for正在跳过最后一行。

Solution: 解:

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

Or if you want to keep the logic you have, you need on your for, add this < , something like this: 或者,如果您想保留自己的逻辑,则需要添加< ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM