c# - 如果 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();
解决方案
我防止用户从 DataGridView 中删除一行(如果它已经为空)的方法是正确的,但我仍然得到一个对象引用未设置为对象错误的实例。我收到此错误是因为我使用 Rows.Count == 0 而不是 CurrentRow == 0 来验证当前行。
正如@G_P 所建议的,使用 Rows.Count,我仍然收到没有数据的行。但是,CurrentRow 对我来说很有意义,它验证了 currentrow 为空。
推荐阅读
- python - 是否可以为每个命令创建一个帮助命令?不和谐.py
- reactjs - 如何在 django 中启用 cors (DJANDO + REACT)
- vue.js - Vuetify 最大化 v-list 的高度
- docker - 在 Mac 上使用 docker compose 从 docker 容器内连接到 Internet
- redis - Redis 速率限制器模式
- angular - 在扩展面板中使用 *ngFor 显示数据
- javascript - 在 chrome 中使用 javascript 设置 SVG 属性
- hadoop - 错误找不到键 log4j.appender.RFA 的值
- delphi - 如何在画布上移动两个位图图像
- javascript - Charts.js 如何拥有 2 个不同大小的 y 轴