【问题标题】:How can I make datagridview can only select the cells in the same column at a time?如何使 datagridview 一次只能选择同一列中的单元格?
【发布时间】:2011-01-29 19:21:36
【问题描述】:

我正在使用 winforms 开发我的应用程序。 我将我的 datagridview 控件的选择模式设置为“CellSelect”,这允许用户选择任意数量的单元格,这些单元格分布在几列中;但我想限制我的用户一次只能选择单列中的单元格,而且我没有任何这种选择模式。

所以如果我想实现这个,我该如何扩展 datagridview 类? 我也认为我可以在更改选择单元格时检查eventHandler,我可能使用户无法选择在多列上传播的单元格,但这不是那么好,我想。

任何其他人可以帮助我找到更好的解决方案吗?

【问题讨论】:

    标签: c# winforms inheritance datagridview


    【解决方案1】:

    你的实现没问题。这正是我所做的。最初我尝试处理 SetSelected...Core 方法,但细节变得笨拙。我选择了以下内容,因为 1) 它可以使用很少的代码,2) 不会干扰其他代码,以及 3) 简单。

    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
    

    【讨论】:

    • 表示感谢,但恐怕性能不会那么好
    • @MemoryLeak:你认为性能会受到影响,如何?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2012-08-09
    相关资源
    最近更新 更多