如何准确确定 DataGridView 中的行数除了新行(带星号的行)?
如果我开始输入新行然后按 Esc 取消它,同时创建的另一个新行将消失,原始行再次成为新行。但它不再将其 IsNewRow
属性设置为 true
。 DataGridView.NewRowIndex
突然设置为 -1
。
如何正确计算除新行以外的行,包括上述特殊情况? ( Temporary reset of NewRowIndex
to -1
(also affecting IsNewRow
) is a "feature" of DataGridView. )
(C# 或 VB – 任何你喜欢的。)
对于那些无法找到上述特殊情况的人——
只需处理 DataGridView.UserDeletedRow
就可以了:
Sub DataGridView1_UserDeletedRow1(sender As Object, e As EventArgs) _
Handles DataGridView1.UserDeletedRow
' reveal problem with DataGridView1.NewRowIndex
Debug.Print($"NewRowIndex={DataGridView1.NewRowIndex}")
' reveal problem with row.IsNewRow
For Each row As DataGridViewRow In DataGridView1.Rows
Debug.Print($"Row {row.Index}: IsNewRow={row.IsNewRow}")
Next
End Sub
步骤:
- 创建 WinForms VB 项目。
- 添加
DataGridView1
。 - 将 2 个文本列添加到
DataGridView1
。 - 添加上述事件处理程序。
- 启动。
- 关注第一列并键入
a
。 - 按 Esc 立即退出编辑模式。
- 查看结果。上面的处理程序打印
NewRowIndex=-1
,但它应该打印数字>= 0
。最后一个IsNewRow
值为false
,但它应该为true
。
最佳答案
查看 MSDN 上的这篇文章:system.windows.forms.datagridview.allowusertoaddrows (仔细阅读备注部分)和这篇 MSDN 论坛帖子 datagridview-cancel-add-new-row
您可以使用 DataGridView.AllowNew
属性作为解决方案的解决方法。
设置
DataGridView.AllowNew = False
这应该删除新的插入行计算 DataGridView 的行数
DataGridView.Rows.Count
或DataGridView.RowCount
(以您的要求为准)再次设置
DataGridView.AllowNew = True
以显示用于添加新记录的空白行(如果需要)
我还没有测试代码片段,但这应该可以解决问题
编辑:
刚找到两篇与您的问题相关的文章,可能对您的阅读有用:
关于c# - 确定 DataGridView 中除新行之外的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020579/