Solution for
DataGridview.CellValueChanged Event
fires multiple times.
|
Datagridview.CellValuechanged event fires multiple times |
- When you use Visual Studio to develop a WinForms application that contains Datagridview CheckBox Column.
One of the Events that you may use to Change the Values in the Cells is [ CellValueChanged ] event.
You will notice 'if you debug your code', that this Event fires multiple times while executing.
- Here is a solution for this multiple firing issue :
Code
Private Sub DatagridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs)
If TypeOf DatagridView1.CurrentCell Is DataGridViewCheckBoxCell Then
Dim ChkCnt As Integer
Dim columnIndex As Integer = OptCol.Index
If e.ColumnIndex = columnIndex Then
Dim isChecked As Boolean = CBool(DatagridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
RemoveHandler DatagridView1.CellValueChanged, AddressOf DatagridView1_CellValueChanged
If isChecked Then
For Each row As DataGridViewRow In DatagridView1.Rows
If row.Index <> e.RowIndex Then
row.Cells(columnIndex).Value = Not isChecked
ChkCnt -= 1
Else
ChkCnt += 1
End If
Next
End If
If ChkCnt < 0 Then
TileBarItem1.Enabled = False
TileBarItem2.Enabled = True
TileBarItem3.Enabled = True
ElseIf ChkCnt = 0 Then
TileBarItem1.Enabled = True
TileBarItem2.Enabled = False
TileBarItem3.Enabled = False
End If
Debug.WriteLine(String.Format("{0} count", ChkCnt.ToString))
End If
End If
End Sub
Solution : Add this new Event [ CurrentCellDirtyStateChanged ]
Private Sub DatagridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs)
If TypeOf DatagridView1.CurrentCell Is DataGridViewCheckBoxCell Then
If DatagridView1.IsCurrentCellDirty Then
DatagridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
AddHandler DatagridView1.CellValueChanged, AddressOf DatagridView1_CellValueChanged
End If
End If
End Sub