2016-12-22 29 views
3

我改編這個問題 how to select rows on cellclick, and also columns on column header click? 成一個單一的DataGridView1_MouseDown事件代碼按多個行或保持「Ctrl」鍵列,因爲它沒有讓我選擇使用「Ctrl鍵多行/列「鍵。如何選擇DataGridView的對象

我想要的是能夠通過按住Ctrl鍵來選擇多行(單擊行索引)或多列(單擊列標題)。我可以很容易地得到一個或另一個(將DataGridViewSelectionMode設置爲FullRowSelect或ColumnHeaderSelect),然後Ctrl可以工作,但我希望在同一個DataGridView上具有這兩種功能。

我覺得我好親近。感謝您的任何提示!

Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown 
    Dim ht As DataGridView.HitTestInfo 
    ht = Me.DataGridView1.HitTest(e.X, e.Y) 
    If e.Button = Windows.Forms.MouseButtons.Left Then 
     If ht.Type = DataGridViewHitTestType.Cell Then 
      DataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect 
      DataGridView1.CurrentCell.Selected = True 
     ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then 
      DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect 
      DataGridView1.Rows(ht.RowIndex).Selected = True 
     ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then 
      DataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect 
      DataGridView1.Columns(ht.ColumnIndex).Selected = True 
     End If 
    End If 
End Sub 

回答

1

我不認爲你將能夠同時使用全柱和全行選擇在同一時間,在運行一些測試後,似乎改變的datagridview的selectionMode是當它被設置什麼的清算選擇...所以除非你創建一個從datagridview繼承的自定義控件並覆蓋它的一些內部組件,否則你可能會被卡住。如果不這樣做,只有這樣,我是能夠實現你想要得到的行爲是離開的datagridview cellselection模式設置爲cellselect,和做手工行/列的選擇:

Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) _ 
    Handles DataGridView1.MouseDown 
    If e.Button = Windows.Forms.MouseButtons.Left Then 
     Dim ht As DataGridView.HitTestInfo = Me.DataGridView1.HitTest(e.X, e.Y) 
     If Not My.Computer.Keyboard.CtrlKeyDown Then DataGridView1.ClearSelection() 
     If ht.Type = DataGridViewHitTestType.Cell Then 
      DataGridView1.CurrentCell.Selected = True 
     ElseIf ht.Type = DataGridViewHitTestType.RowHeader Then 
      For i As Integer = 0 To DataGridView1.Columns.Count - 1 
       DataGridView1.Rows(ht.RowIndex).Cells(i).Selected = True 
      Next 
     ElseIf ht.Type = DataGridViewHitTestType.ColumnHeader Then 
      For i As Integer = 0 To DataGridView1.Rows.Count - 1 
       DataGridView1.Rows(i).Cells(ht.ColumnIndex).Selected = True 
      Next 
     End If 
    End If 
End Sub 
+0

喜爲soohoonigan感謝花時間回答! 肯定比我的代碼更好,謝謝。從表面上看,Ctrl的行爲按預期工作,但它並不理想:像DataGridView1.SelectedColumns沒有更新,「Shift」不能按預期工作......我想我也可以手動編碼,看起來像一個很多麻煩,但我認爲我會留下這一點爲以後的潛在改進。再次感謝。 – Zingapuro

+0

我很困惑,爲什麼DataGridView1.Rows(ht.RowIndex).Selected = True不行?只是保持假... – Zingapuro