将单元格单击事件处理程序添加到datagridview?

时间:2016-07-15 13:22:30

标签: vb.net datagridview

我有三列,第一列是文本框,第二列是复选框,第三列是文本框。我想将click事件添加到第三列,如果用户单击该单元格,它将自动选中并取消选中该行的第二个复选框列。我尝试了这个,但它没有用。

AddHandler datagridview1.MouseClick, AddressOf form1.datagridview1_MouseClick

2 个答案:

答案 0 :(得分:0)

查看CellClick事件。 https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick(v=vs.110).aspx

类似的东西:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    With DataGridView1
        .Rows.Add({"John Smith", 1})
        .Rows.Add({"Jane Doe", 0})
    End With
    AddHandler DataGridView1.CellClick, AddressOf DataGridView1_CellClick
End Sub

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)
    If e.RowIndex < 0 Then Exit Sub

    Dim dgv As DataGridView = CType(sender, DataGridView)
    If Not TypeOf dgv.Rows(e.RowIndex).Cells(e.ColumnIndex) Is DataGridViewCheckBoxCell Then Exit Sub

    Dim cell As DataGridViewCheckBoxCell = CType(dgv.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewCheckBoxCell)

    cell.Value = Not CBool(cell.Value)
    dgv.EndEdit()
End Sub

End Class

答案 1 :(得分:0)

只需将子程序上的Handle类型切换为“Handles DataGridView1.CellClick”即可。例如:

 Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    Dim tempView = DirectCast(sender, DataGridView)

    For Each cell As DataGridViewTextBoxCell In tempView.SelectedCells
        If cell.ColumnIndex = 1 Then
            Dim tempCheckBoxCell As DataGridViewCheckBoxCell = tempView("column1", cell.RowIndex)
            tempCheckBoxCell.Value = True
        End If
    Next
End Sub

另外,快速注意 - 您需要将每个循环中找到的单元格类型调整为您正在使用的任何类型的单元格;在示例中,我将column2设置为一个简单的文本框类型单元格。