WinForms中DataGridView错误提示信息无法显示问题求助
解决DataGridView验证时错误标记与文本不显示的问题
你遇到的问题核心在于:当在CellValidating事件中设置e.Cancel = true时,单元格会保持编辑状态,而DataGridView默认不会在编辑中的单元格显示错误图标。另外,错误文本的显示依赖于控件的ShowCellErrors属性(默认启用,但可检查确认)。
以下是两种可行的处理方案:
方案1:强制用户修正错误后才能离开单元格
这种情况下,你需要在验证失败时设置单元格的ErrorText,手动刷新单元格以显示错误标记,同时保留e.Cancel = true锁定单元格:
private void YourDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv == null) return; // 示例:验证第二列输入不为空且是数字 if (e.ColumnIndex == 1) { string input = e.FormattedValue.ToString().Trim(); if (string.IsNullOrEmpty(input) || !int.TryParse(input, out _)) { // 设置错误文本 dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "请输入有效的整数,不能为空"; // 锁定单元格,强制用户修正 e.Cancel = true; // 手动刷新单元格,触发错误图标显示 dgv.InvalidateCell(e.ColumnIndex, e.RowIndex); // 弹出提示告知用户错误详情 MessageBox.Show("输入无效:请输入非空的整数"); } else { // 验证通过,清除错误文本 dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty; } } }
方案2:允许用户离开单元格,保留错误标记待后续修正
这种方式更灵活,用户可以先操作其他单元格,之后再回来修正错误,错误图标会自动显示(因为单元格退出了编辑状态):
private void YourDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv == null) return; if (e.ColumnIndex == 1) { string input = e.FormattedValue.ToString().Trim(); if (string.IsNullOrEmpty(input) || !int.TryParse(input, out _)) { dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "请输入有效的整数,不能为空"; MessageBox.Show("输入无效:请输入非空的整数"); // 不设置e.Cancel,允许用户离开单元格 } else { dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = string.Empty; } } }
关键注意事项
- 确保DataGridView的
ShowCellErrors属性设置为true(默认值为true,若被修改需手动开启)。 - 当单元格处于编辑状态时,错误图标不会自动渲染,必须调用
InvalidateCell强制刷新才能显示(对应方案1)。 - 若使用方案2,用户将鼠标悬停在错误图标上时,会自动显示你设置的
ErrorText内容。
内容的提问来源于stack exchange,提问作者Sergej_S
相关产品推荐
相关产品推荐

