.net 禁用数据网格视图中的行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/71423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:52:56  来源:igfitidea点击:

Disable selection of rows in a datagridview

.netwinformsdatagridviewuser-interface

提问by Niki

I want to disable the selection of certain rows in a datagridview.

我想禁用 datagridview 中某些行的选择。

It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)

必须可以在 winform 中显示的 datagridview 中删除一个或多个 datagridview 行的 select 属性。目标是用户不能选择某些行。(视情况而定)

Thankx,

谢谢,

回答by szevvy

If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.

如果 SelectionMode 是 FullRowSelect,那么您需要为该 DataGridView 覆盖 SetSelectedRowCore,而不是为您不想选择的行调用基本 SetSelectedRowCore。

If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.

如果 SelectionMode 不是 FullRowSelect,您将需要额外覆盖 SetSelectedCellCore(并且不为您不想选择的行调用基础 SetSelectedCellCore),因为 SetSelectedRowCore 只会在您单击行标题而不是单个单元格时启动。

Here's an example:

下面是一个例子:

public class MyDataGridView : DataGridView
{
    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        if (selected && WantRowSelection(rowIndex))
        {
            base.SetSelectedRowCore(rowIndex, selected);
        }
     }

     protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
     {
         if (selected && WantRowSelection(rowIndex))
         {
            base.SetSelectedRowCore(rowIndex, selected);
          }
     }

     bool WantRowSelection(int rowIndex)
     {
        //return true if you want the row to be selectable, false otherwise
     }
}

If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.

如果您使用的是 WinForms,请打开相关表单的 Designer.cs,并将 DataGridView 实例的声明更改为使用这个新类而不是 DataGridView,并替换 this.blahblahblah = new System.Windows.Forms。 DataGridView() 指向新类。

回答by Asad Naeem

Private Sub dgvSomeDataGridView_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgvSomeDataGridView.SelectionChanged
        dgvSomeDataGridView.ClearSelection()
End Sub