How can I make datagridview can only select the cells in the same column at a time?
I am using winforms to develop my application. And I set my datagridview control's selectionmode to "CellSelect", and this allow the user to select as many cells as he want which spread over several columns; but I want to constraint my user can only select cells in single column at a time, and there isn't any such kind of selectionmode for me.
So If I want to implement this, ho开发者_如何学JAVAw can I extend the datagridview class ? I also think that I can check in eventhandler whenever the selection cells are changed, through which I might make the user can not select cells spread over multiple columns, but this is not that good, I think.
Can any other people help me to find out a better solution ?
Your implementation is okay. This is exactly what I did. Initially I tried to deal with the SetSelected...Core methods, but the details got clumbersome. I settled on the following because 1) it works with little code, 2) doesn't interfere with other code, and 3) 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
精彩评论