How can I get a datagridview to select only cells in one column at a time?

I use winforms to develop my application. And I set my datagridview control selection method to "CellSelect", and this allows the user to select as many cells as he wants, which apply to multiple columns; but I want to limit that my user can select cells in only one column at a time, and for me there is no such type selectionmode.

So, if I want to implement this, how to extend the datagridview class? I also think that I can check the event handler whenever the selection cells change, so that I can force the user not to select the cells spread over several columns, but I think that it is not.

Can other people help me find the best solution?

+4
source share
1 answer

Your implementation is fine. This is exactly what I did. At first I tried to figure out the SetSelected ... Core methods, but the details became clumsy. I settled on the following: 1) it works with a small code, 2) it does not interfere with another code, and 3) it is simple.

Public Class DataGridView Inherits System.Windows.Forms.DataGridView Protected Overrides Sub OnSelectionChanged(ByVal e As System.EventArgs) Static fIsEventDisabled As Boolean If fIsEventDisabled = False Then If Me.SelectedCells.Count > 1 Then Dim iColumnIndex As Integer = Me.SelectedCells(0).ColumnIndex fIsEventDisabled = True ClearSelection() SelectColumn(iColumnIndex) 'not calling SetSelectedColumnCore on purpose fIsEventDisabled = False End If End If MyBase.OnSelectionChanged(e) End Sub Public Sub SelectColumn(ByVal index As Integer) For Each oRow As DataGridViewRow In Me.Rows If oRow.IsNewRow = False Then oRow.Cells.Item(index).Selected = True End If Next End Sub End Class 
+1
source

Source: https://habr.com/ru/post/1304646/


All Articles