首页 > 解决方案 > 如果 DataGridView 已经为空,如何防止用户删除行?

问题描述

在我的 Windows 窗体应用程序中,我有一个类别表单,其中包含不同的类别及其 ID、名称和描述。该表单还包含用于不同操作的几个按钮,包括添加类别、编辑和删除类别。

在某些情况下,如果类别 DataGridView 需要为空,我如何通知用户 gridview 已经为空并且无法进一步删除。我想通过消息框通知他没有更多行要删除。以下是我在删除按钮上使用的代码。

private void btnDelete_Click(object sender, EventArgs e)
    {
        if (dgvCategories.Rows.Count == 0)
        {
            DataAccess.WarnUser("No categories to delete.");
            txtCategoryName.Focus();
            return;
        }

        string categoryName = dgvCategories.CurrentRow.Cells[1].Value.ToString();
        if (DataAccess.AskUser("Are you sure want to delete this permanently?", "Confirm Deletion") == true)
        {
            string categoryId = dgvCategories.CurrentRow.Cells[0].Value.ToString();
            Categories.Delete(categoryId);
            FillGrid();
        }
    }

但我收到“对象引用未设置为对象的实例”。这条线上的错误。我在这里做错了什么?

string categoryName = dgvCategories.CurrentRow.Cells[1].Value.ToString();

标签: c#asp.netwinformsdesktop-application

解决方案


我防止用户从 DataGridView 中删除一行(如果它已经为空)的方法是正确的,但我仍然得到一个对象引用未设置为对象错误的实例。我收到此错误是因为我使用 Rows.Count == 0 而不是 CurrentRow == 0 来验证当前行。

正如@G_P 所建议的,使用 Rows.Count,我仍然收到没有数据的行。但是,CurrentRow 对我来说很有意义,它验证了 currentrow 为空。


推荐阅读