|
DataGridView 不显示最下面的新行:
通常 DataGridView 的最下面一行是用户新追加的行(行头显示 * )。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置为 False。
[VB.NET]
' 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = False
[C#]
// 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = false;
但是,可以通过程序: DataGridViewRowCollection.Add 为 DataGridView 追加新行。
补足: 如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataView.AllowAdd
属性为 False 来达到同样的效果。
DataGridView 判断新增行:
DataGridView的AllowUserToAddRows属性为True时也就是允许用户追加新行的场合下,DataGridView的最后一行就是新追加的行(*行)。使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过DataGridView.NewRowIndex 可以获取新行的行序列号。在没有新行的时候,NewRowIndex = -1。 [VB.NET]
If DataGridView1.CurrentRow.IsNewRow Then
Console.WriteLine("当前行为新追加行。")
Else
Console.WriteLine("当前行不是新追加行。")
End If
DataGridView 行的用户删除操作的自定义:
1) 无条件的限制行删除操作。
默认时,DataGridView 是允许用户进行行的删除操作的。如果设置 DataGridView对象的AllowUserToDeleteRows属性为 False 时, 用户的行删除操作就被禁止了。
[VB.NET]
' 禁止DataGridView1的行删除操作。
DataGridView1.AllowUserToDeleteRows = False
[C#]
// 禁止DataGridView1的行删除操作。
DataGridView1.AllowUserToDeleteRows = false;
但是,通过 DataGridViewRowCollection.Remove 还是可以进行行的删除。
补足: 如果 DataGridView 绑定的是 DataView 的话,通过 DataView.AllowDelete 也可以控制行的删除。
2) 行删除时的条件判断处理。
用户在删除行的时候,将会引发 DataGridView.UserDeletingRow 事件。 在这个事件里,可以判断条件并取消删除操作。
[VB.NET]
' DataGridView1 的 UserDeletingRow 事件
Private Sub DataGridView1_UserDeletingRow(ByVal sender As Object, _
ByVal e As DataGridViewRowCancelEventArgs) _
Handles DataGridView1.UserDeletingRow
' 删除前的用户确认。
If MessageBox.Show("确认要删除该行数据吗?", "删除确认", _
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> _
Windows.Forms.DialogResult.OK Then
' 如果不是 OK,则取消。
e.Cancel = True
End If
End Sub
[C#]
// DataGridView1 的 UserDeletingRow 事件
private void DataGridView1_UserDeletingRow(
object sender, DataGridViewRowCancelEventArgs e)
{
// 删除前的用户确认。
if (MessageBox.Show("确认要删除该行数据吗?", "删除确认",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question) != DialogResult.OK)
{
// 如果不是 OK,则取消。
e.Cancel = true;
}
}
(责任编辑:admin) |