mir*_*lav 5 c# vb.net datagridview winforms
除了新行(带星号的行)之外,我如何才能确定DataGridView中的行数?
如果我开始键入新行然后按下取消它,则Esc在此期间创建的另一个新行将消失,原始行将再次成为新行.但它不再有其IsNewRow属性设置true.并且DataGridView.NewRowIndex突然被设定为-1.
如何正确计算除新行之外的行,包括上述特殊情况?(临时重置NewRowIndex为-1(也影响IsNewRow)是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
Run Code Online (Sandbox Code Playgroud)
脚步:
DataGridView1.DataGridView1.a.NewRowIndex=-1,但它应该打印数字>= 0.最后一个IsNewRow值是false,但它应该是true.没有其他事件(除了已经使用的事件DataGridView.UserDeletedRow)适合用于涵盖特殊情况的计算。在这种情况下,键值暂时不正确 \xe2\x80\x93 请参阅源代码。
DataGridView唯一的方法似乎是从和的 .NET 参考源中进行计算DataGridViewRow。
下面的计算假设
\nDataGridView.AllowUserToAddRows当且仅当是时才存在新行true。我们来计算一下:
\n= DataGridView1.Rows.Count - (DataGridView1.AllowUserToAddRows ? 1 : 0)\nRun Code Online (Sandbox Code Playgroud)\n与有问题的原始属性不同,这些计算似乎总是成功:
\nDataGridView.NewRowIndex= (DataGridView1.AllowUserToAddRows ? DataGridView1.Rows.Count - 1 : -1)\nRun Code Online (Sandbox Code Playgroud)\nDataGridViewRow.IsNewRow= row.DataGridView.AllowUserToAddRows && (row.Index == row.DataGridView.Rows.Count - 1)\nRun Code Online (Sandbox Code Playgroud)\n作为vb.net扩展方法实现:
\n= DataGridView1.Rows.Count - (DataGridView1.AllowUserToAddRows ? 1 : 0)\nRun Code Online (Sandbox Code Playgroud)\n在通过对这些方法的调用替换标准调用之后,我注意到我的项目中修复了其他几个细微的错误,这似乎与新记录行的存在有关。
\n