温馨提示×

c#中如何用datagridview删除空白行

c#
小亿
92
2024-03-27 18:35:32
栏目: 编程语言

在C#中,可以通过遍历DataGridView的行,并判断每一行的值是否为空来删除空白行。以下是一个示例代码:

private void RemoveEmptyRows(DataGridView dgv)
{
    List<DataGridViewRow> rowsToRemove = new List<DataGridViewRow>();

    foreach (DataGridViewRow row in dgv.Rows)
    {
        bool isEmpty = true;

        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.Value != null && !string.IsNullOrWhiteSpace(cell.Value.ToString()))
            {
                isEmpty = false;
                break;
            }
        }

        if (isEmpty)
        {
            rowsToRemove.Add(row);
        }
    }

    foreach (DataGridViewRow rowToRemove in rowsToRemove)
    {
        dgv.Rows.Remove(rowToRemove);
    }
}

你可以在需要删除空白行的地方调用这个方法,传入要操作的DataGridView对象即可。

0