禁用datagridview中的行选择
时间:2020-03-05 18:55:41 来源:igfitidea点击:
我想禁用datagridview中某些行的选择。
必须有可能删除winform中显示的datagridview中一个或者多个datagridview行的select属性。目标是用户不能选择某些行。 (取决于条件)
谢谢,
解决方案
回答
如果SelectionMode为FullRowSelect,则需要为该DataGridView覆盖SetSelectedRowCore,而不要为不需要选择的行调用基本SetSelectedRowCore。
如果SelectionMode不是FullRowSelect,则我们将要额外覆盖SetSelectedCellCore(并且不要为不需要选择的行调用基本SetSelectedCellCore),因为SetSelectedRowCore仅在单击行标题而不是单个单元格时才起作用。
这是一个例子:
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 } }
如果我们使用的是WinForms,请针对相关表单打开designer.cs,并更改DataGridView实例的声明以使用此新类代替DataGridView,并替换this.blahblahblah = new System.Windows.Forms。 DataGridView()指向新类。