2010-03-20 74 views
4

我正在使用winforms來開發我的應用程序。 而我將我的datagridview控件的選擇模式設置爲「CellSelect」,這允許用戶選擇儘可能多的單元格,他希望分佈在多個列上;但我想約束我的用戶一次只能選擇單個列中的單元格,並且我沒有任何這種類型的選擇模式。我該如何讓datagridview一次只能選擇同一列中的單元格?

所以如果我想實現這個,我該如何擴展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 
+0

注意到謝謝,但恐怕表現不會那麼好 – MemoryLeak 2010-03-21 00:55:28

+0

@MemoryLeak:你相信會有一場表演打擊,怎麼樣? – AMissico 2010-03-21 01:50:25

相關問題