Reputation: 2111
I have a DataGridView and sometimes I use the CellValueChanged Event but othertime I don't want it to trigger. Is there a way that I can remove an event sub and then restore it.
I have 5 columns with a ComboBox. After licking one, and then another, the line bellow keeps repeating until stack crashes
Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
Try
Debug.Print("entered the EditingControlShowing")
Dim ColName As String = Me.DataGridView1.Columns(Me.DataGridView1.CurrentCell.ColumnIndex).Name
If ColName = "Col1" Or ColName = "Col2" Or ColName = "Col3" Or ColName = "Col4" Or ColName = "Col5" Then
'the column you want to cast
Dim cmb As ComboBox = TryCast(e.Control, ComboBox)
RemoveHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
AddHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub cmb_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Try
Debug.Print("about to update cell") <<===== this line just repeats until stack crashes
Me.DataGridView1.Rows(Me.DataGridView1.CurrentRow.Index).Cells(Me.DataGridView1.CurrentCell.ColumnIndex).Value = CType(sender, ComboBox).SelectedItem
UpdateAvgColumn(Me.DataGridView1.CurrentRow.Index)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub UpdateAvgColumn(ByVal r As Integer)
Dim avg As Single = 0.0
Debug.Print("UpdateAvgColumn")
If CInt(Me.DataGridView1.Rows(r).Cells("Col1").Value) <> 0 And CInt(Me.DataGridView1.Rows(r).Cells("Col2").Value) <> 0 And _
CInt(Me.DataGridView1.Rows(r).Cells("Col3").Value) <> 0 And CInt(Me.DataGridView1.Rows(r).Cells("Col4").Value) <> 0 And _
CInt(Me.DataGridView1.Rows(r).Cells("Col5").Value) <> 0 Then
avg = CSng((CInt(Me.DataGridView1.Rows(r).Cells("Col1").Value) + CInt(Me.DataGridView1.Rows(r).Cells("Col2").Value) + _
CInt(Me.DataGridView1.Rows(r).Cells("Col3").Value) + CInt(Me.DataGridView1.Rows(r).Cells("Col4").Value) + _
CInt(Me.DataGridView1.Rows(r).Cells("Col5").Value)) / 5)
End If
Me.DataGridView1.Rows(r).Cells("AvgCol").Value = avg
End Sub
Upvotes: 0
Views: 320
Reputation: 19618
Yes, you can remove event handlers, by using RemoveHandler method. But the better approach will be validate the condition in the event and do process or ignore.
Upvotes: 1