温馨提示×

c#中怎么用datagridview删除空白行

c#
小亿
164
2024-01-12 04:30:10
栏目: 编程语言

要删除DataGridView中的空白行,可以按照以下步骤进行操作:

  1. 遍历DataGridView的所有行:

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        // ...
    }
    
  2. 在每一行中检查所有单元格的值是否为空:

    bool isEmptyRow = true;
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells[j].Value.ToString()))
        {
            isEmptyRow = false;
            break;
        }
    }
    
  3. 如果行为空白行,则删除该行:

    if (isEmptyRow)
    {
        dataGridView1.Rows.RemoveAt(i);
    }
    

完整的代码示例:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    bool isEmptyRow = true;
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells[j].Value.ToString()))
        {
            isEmptyRow = false;
            break;
        }
    }
    if (isEmptyRow)
    {
        dataGridView1.Rows.RemoveAt(i);
    }
}

注意:在删除行后,行索引会改变,因此需要递减i的值,以便正确遍历所有行。

0