如何:防止在 Windows 窗体 DataGridView 控件中添加和删除行

有时想要阻止用户在 DataGridView 控件中输入新的数据行或删除现有行。 AllowUserToAddRows 属性指示新记录的行是否显示在控件底部,而 AllowUserToDeleteRows 属性指示行是否可删除。 以下代码示例使用这些属性,并设置 ReadOnly 属性以使控件完全只读。

Visual Studio 中对此任务提供支持。 另请参见如何:使用设计器防止在 Windows 窗体 DataGridView 控件中添加和删除行

示例

private void MakeReadOnly()
{
    dataGridView1.AllowUserToAddRows = false;
    dataGridView1.AllowUserToDeleteRows = false;
    dataGridView1.ReadOnly = true;
}
Private Sub MakeReadOnly()

    With dataGridView1
        .AllowUserToAddRows = False
        .AllowUserToDeleteRows = False
        .ReadOnly = True
    End With

End Sub

编译代码

此示例需要:

另请参阅