2017-01-18 128 views
0

我在一个新项目上工作,该项目需要用户在datagridview中多行选择/取消选择,只需在触摸屏上轻敲一下。datagridview中的多项选择

的形式应该是这样的:

Form Screenshot http://117.imagebam.com/download/PBhJJNednkL1q0JzMF8j_g/52716/527152884/test%20lecture%20scanner.PNG

对于为例,如果用户想要删除的行2和5,他只需要在每一行一次点击选择/取消选择它们。选择完成后,他点击“删除行”按钮。

我已经尝试玩没有成功的CellClick事件!

有人可以有线索我该如何处理这个问题?

+2

这通常是电网的正常行为的功能,并通过按住Ctrl键,你左键单击列标题来完成。网格属性可能会控制选择类型。 – DonBoitnott

+0

由于操作员没有键盘,我想要一个“模拟”CTRL键的功能! – Boushard

回答

1

MultiSelect属性设置为TrueSelectionModeFullRowSelect后,您可以使用List存储选择,你的DataGridView排。

CellClick您可以添加/从你的List删除行,上RowPostPaint您可以选择一行,如果它包含在ListRowsRemoved你要清楚的List

Private intSelectedRows As New List(Of Integer) 

Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick 

    With CType(sender, DataGridView) 

     Dim intRow As Integer = .CurrentRow.Index 

     If Not Me.intSelectedRows.Contains(intRow) Then 
      Me.intSelectedRows.Add(intRow) 
     Else 
      .CurrentRow.Selected = False 
      Me.intSelectedRows.Remove(intRow) 
     End If 

    End With 

End Sub 

Private Sub DataGridView1_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint 

    If Me.intSelectedRows.Contains(e.RowIndex) Then 
     CType(sender, DataGridView).Rows(e.RowIndex).Selected = True 
    End If 

End Sub 

Private Sub DataGridView1_RowsRemoved(sender As Object, e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles DataGridView1.RowsRemoved 

    Me.intSelectedRows.Clear() 

End Sub 

如果你想明确的选择,你可以使用此代码:

Private Sub btnClearSelectedRows_Click(sender As System.Object, e As System.EventArgs) Handles btnClearSelectedRows.Click 

    For Each intSelectedRow As Integer In Me.intSelectedRows 
     Me.DataGridView1.Rows(intSelectedRow).Selected = False 
    Next intSelectedRow 

    Me.intSelectedRows.Clear() 

End Sub 
+0

像魅力一样工作!正是我在寻找的! 非常感谢你@tezzo – Boushard

+0

刚刚测试了一点,但我遇到了一个问题。如果我想清除此方法所做的选择,除了重新点击已选择的所有行外,我该如何继续?我试过clearselection但没有成功。 – Boushard

+0

答案更新了! – tezzo