1

I have three columns, first column is textbox, second column is checkbox, third column is textbox. I want to add a click event to the third column where if a user click on that cell, it will automatically checkmark and uncheckmark the second checkbox column of that row. I tried this but it's not working.

AddHandler datagridview1.MouseClick, AddressOf form1.datagridview1_MouseClick

2 Answers 2

1

just need to switch your Handle type on the subroutine to "Handles DataGridView1.CellClick". Example:

 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

Also, quick note - you will need to adjust the cell type found in the for each loop to whatever type of cell you are using; in the example I had column2 set to a simple textbox type cell.

Sign up to request clarification or add additional context in comments.

8 Comments

How would i go about unchecking the checkbox?
Add a condition where the tempCheckboxCell.value = true to check true if it is currently false, and false if true
let me know if that helps or if you need an example
I got it, reason it was firing twice was because Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick, needed to delete the handles part.
Ah you already had a handler/reference to the sub, good deal glad it's all working for ya :)
|
0

Look at the CellClick event. https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick(v=vs.110).aspx

Something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.