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

   2025-02-05 6940
核心提示:要删除DataGridView中的空白行,可以按照以下步骤进行操作:遍历DataGridView的所有行:for (int i = 0; idataGridView1.Rows.Co

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

遍历DataGridView的所有行:

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

完整的代码示例:

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的值,以便正确遍历所有行。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言