Event handler not removing itself? - vb.net

At the beginning of a VB .NET function I remove an event handler and add it again at the end of the function because the function's code would trigger those events and I do not want them to trigger for the duration of the function. This usually works, but I have run into a few situations where the event still gets called even though I have already removed it. Sometimes removing it twice at the beginning of the function fixes it, but other times no matter how many times I remove it, it still fires. Any ideas on what could be causing this?
Edit
The code is in a Form that has a virtual mode datagridview. I want to run some operations that will trigger the CellValueNeeded event for the datagridview without that event being fired (because it will interfere).
Public Sub DoEventRaisingStuff()
RemoveHandler grid.CellValueNeeded, AddressOf grid_CellValueNeeded
'Do things that would trigger CellValueNeeded
AddHandler grid.CellValueNeeded, AddressOf grid_CellValueNeeded
End Sub
Removing the handler multiple times does not prevent the event from firing, so it doesn't seem to be added multiple times somewhere else by accident.
Is there a way to find out what event handlers are active?

If the event handling code is being called then one of two things is happening:
You aren't removing the event handler.
You are adding the event handler multiple times. This is the more usual case.
In the past the only way I've been able to spot 2. is to find all the places where the event handler is added (hopefully only one or two) and put break points on those lines. I've then run the application under the debugger and found that it breaks more times than I expect. I use the call stack to work out why - it's always me putting the add code in the wrong place (on a button press rather than on form instantiation for example).
You can do the same with the removal code. Count the number of times each break point is hit and if they're not the same work back up the call stack to see if you can work out why.

Use class scoped flag in the function and check the flag in the event handler.
i.e.:
Private RunFunction as Boolean = False
...
Private Sub MyEvent(e as system.eventargs) handles myObject.Method
If RunFunction Then
...
End If
End Sub
...
Private Sub MyFunction()
RunFunction = False
...
RunFunction = True
End Sub

Related

Label Text not updating even when using Refresh, Invalidate, and DoEvents

My code is designed to be a control system for a 2-axis motion system. I have 2 drives that each output a count of their steps. I can read the device, update a property, and update the text field of a label. However, it does not update the form. When I use a message box, I can display the text value being correct, but nothing updates the label.
I'm happy to try any suggestions, but I've been fighting this for about 16 hours and I'm at my wits end - as evidenced by the clear overkill/terrible coding that is shown in the code. I can't understand why it's not updating.
Additionally, a manual button with all versions seen below to refresh a form doesn't update the control.
Direction, recommendations?
Private Sub PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
If TraverseController.InvokeRequired Then
TraverseController.Invoke(
New EventHandler(Of EventArgs)(AddressOf PositionChanged), sender, e)
Return
End If
'RaiseEvent PropertyChanged(TraverseController, New System.ComponentModel.PropertyChangedEventArgs("Position"))
MessageBox.Show(TraverseController.lblLinearDrivePosDisp.Text)
TraverseController.lblLinearDrivePosDisp.Text = CStr(_position)
Application.DoEvents()
TraverseController.lblLinearDrivePosDisp.ResetBindings()
TraverseController.GBDrivePositionDisp.Refresh()
TraverseController.lblLinearDrivePosDisp.Refresh()
TraverseController.Refresh()
TraverseController.Invalidate()
TraverseController.Update()
Application.DoEvents()
MessageBox.Show(TraverseController.lblLinearDrivePosDisp.Text)
End Sub
Assumption: TraverseController is form's class name.
This looks like a VB default form instance issue. It is apparent that you are trying to properly marshal control interaction back to the UI thread by using checking TraverseController.InvokeRequired. However, due to the way these default instance are created, TraverseController.InvokeRequired is creating a new instance of TraverseController on the secondary thread and all subsequent code is modifying that instance and not the one created on the UI thread.
One way to deal with this is to pass a synchronizing control instance to the class where PositionChanged changed method is defined and check that control's InvokeRequired method instead of TraverseController.InvokeRequired. If the containing class is itself a UI control, then use that class instance (Me.InvokeRequired).

vb.net control's events only when user clicks [duplicate]

Consider a simple .NET form with a couple of radio buttons and a checkbox.
Each of the radio buttons has a CheckedChanged handler setup that performs some action based on the state of the checkbox.
My problem is, when I initialize on the default radiobutton to be checked (from the designer properties window) the CheckedChanged event is fired for that radio button, but the Checkbox hasn't been initialized yet so I either get a null pointer exception or the wrong value is used in the handler. Either way, I don't want that handler code to be run unless the user picks a radio button after the form has been loaded.
I currently get around this by not initializing the radio button, but I need to set that default eventually and the best place is from the designer. I also can add a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack.
What can I do to prevent that handler from running its code?
To make it feel slightly less dirty, if you initialize the controls in the constructor of the form you might be able to use the forms IsHandleCreated property rather than your own bool to check if it should actually validate or not.
I would think that normally you wouldn't want to validate anything before it's been shown for the first time and handle isn't created until it is.
Code Example:
Private Sub myRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles myRadioButton.CheckedChanged
If myRadioButton.Checked AndAlso myRadioButton.IsHandleCreated Then
'Do Work
End If
End Sub
"I also can put a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack."
It's also the easist and best way to do it!
Lets say .NET provides a neat way to turn an and off all the event handlers until the form is loaded. Even just the ones YOU are handling. It would still not be sufficiently flexible to disable what you wanted to enable but disable what you didn't. Often form setups happen and you want the events to fire. Also the form won't build right if no events fire.
The easy solution is to declare an initializing variable:
Private Initializing as boolean = True
Private Sub rb_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbNuevos.CheckedChanged, RbDesaparecidos.CheckedChanged, RbModificados.CheckedChanged, RbNoDesap.CheckedChanged, RbDesHoy.CheckedChanged, RbChT.CheckedChanged
if Initializing then return
'Your Code
End Sub
Public Sub New()
' Llamada necesaria para el Diseñador de Windows Forms.
InitializeComponent()
' Agregue cualquier inicialización después de la llamada a InitializeComponent().
initializing = false
end sub
Most sophisticated: Remove the "handles" from the method, and use AddHandler on the new method.
Public Sub New()
' Llamada necesaria para el Diseñador de Windows Forms.
InitializeComponent()
' Agregue cualquier inicialización después de la llamada a InitializeComponent().
AddHandler RbChT.CheckedChanged, AddressOf rb_CheckedChanged
end sub
For radiobutton see Hans Olsson answer
For numeric up down, do it like this
Private Sub myNumeric_ValueChanged(sender As Object, e As EventArgs) Handles myNumeric.ValueChanged
If myNumeric.Value >= 0 AndAlso myNumeric.IsHandleCreated Then
'Do the work
End If
End Sub
The keyword is myNumeric.Value and IsHandleCreated
Yet another way:
Private Sub dgvGroups_CellValueChanged(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvGroups.CellValueChanged
If Me.Visible = False Then Exit Sub ' Sub gets called on form load which causes problems
wksGroups.Cells(e.RowIndex + 1, 1) = dgvGroups.Item(e.ColumnIndex, e.RowIndex).Value
wksGroups.Cells(1, 5) = dgvGroups.RowCount
One thing I've found that works is adding the events manually after you load the form.
To do this you can simply go into the generated form code found in the designer file of that form, and pull out the lines that add the event. It would look something like this:
this.controlName.CheckedChanged += new System.EventHandler(this.controlName_CheckedChanged);
Then put all of these calls into a method that you call after the InitializeComponent call in your form's constructor.
Just in case anyone is still searching for this the event is fired upon initializing the form BUT the form is not yet visible, Also Say that you have a foreign key relationship upon which you have a default value needed issue that gets fired every row update too. So the following code worked for me....
if (Visible && !(e.ColumnIndex == 0))
{
phoneEdited = true;
MessageBox.Show("A Phone entry has been entered");
}
Don't set checked on a control that really does much in designer.
The global flag and conditional exits where needed.
Try..Catch the sore spots to ignore a meaningless exception.
(Using VS 2017) It appears to me that it is an annoyance but not a bug. It is consistent with the model in use. The event is fired by normal operation of code, but code I did not write (but can access where fools fear to tread) and where there appears to be no (decent) place earlier in the normal flow to anticipate it.
The cleanest answer seems to be not to check radio button or checkbox controls in the designer at all if they trigger any significant code. Instead these controls should be changed by code (e.g. checked = true) in the Load event (for example) AFTER all the initialization is done.
There is no loss of flexibility here since both are fixed before the build, only in different places. The event handlers will handle it exactly as if a user had clicked the control in the natural flow of a well designed GUI application. (This reminds me of the ancient RPG proverb "Don't buck the cycle". (Anyone here remember RPG? I, not part of IBM-oriented team, never used it but had interesting discussions with some who did. ) Pre-checking controls hits the wrong part of the VS cycle.)
If for any reason that will not work, the next best thing is the kludge suggested elsewhere of a single status boolean initialized false and set true at the appropriate time with conditional exits in the necessary places to prevent them from crashing until then. It will get the job done, but it's ugly. Better than failure.
Another thing I tried before I decided that designer level pre-set checks were the problem and there was a very acceptable alternative was to put the danger spots in a Try..Catch to be able to ignore the exception. Also a kludge.
For the cleanest code, reverse the True/False approach used in some other examples. Focus on 'ready' rather than 'busy'. Here's an example for a Windows Form:
At the Class level, add Private app_ready As Boolean (it will be False by default).
At the end of the Form.Shown event handler, add app_ready = True.
In each control event handler where it's needed, add:
If app_ready Then
' code
End If
Starting a routine with something like If initialising Then Exit Sub just doesn't feel right!
Maybe for some functionality you can use the click event instead of the check changed event.
I put a public variable in the Module1 file
Dim Public bolForm_LoadingTF as Boolean = True
In each formLoad event I put
bolForm_LoadingTF = True
In each control with an OnSelectedIndexChanged
event I put if bolForm_LoadingTF = True then Exit Sub
At the end of the form load event I put
bolForm_LoadingTF = False
I am probably breaking a bunch of rules but this works
for me.

Ensure a method only fires once when an event is triggered multiple times in Winforms newer method in .NET 4.5

So essentially I have wired up three text boxes to do a smart filter and want to let a user do a multi filter. The only problem was that it was firing too frequently and I want to have it fire after a delay. The event for 'TextChanged' is wired up to basically run and I have a simplified example of what I want:
I have a simple Winforms UI with two text boxes: "txtWait" and "txtTest". In the front end code the properties are default and the text are:
txtWait.Text = 1000
txtTest.Text = "Test Text I have here to look at"
A way to test this is to just hit the backspace a few times and wait. I would want only the last text to show once. I just got this part to work but the resetting it not occurring as I would expect. I would expect a person could hit backspace, backspace, (only a half a second had passed), backspace(clock resets and new wait begins).
And my code behind is:
Public Class DelayBeforeAction
Private _loaded As Boolean = False
Private _sw As Stopwatch = New Stopwatch()
Public Sub New()
InitializeComponent()
_loaded = True
End Sub
Private Sub txtTest_TextChanged(sender As Object, e As EventArgs) Handles txtTest.TextChanged
If _loaded Then
_sw.Start()
DelayExecute(Sub() If _sw.ElapsedMilliseconds > CInt(txtWait.Text) Then _sw.Reset() : MessageBox.Show(txtTest.Text) Else _sw.Reset(), CInt(txtWait.Text))
End If
End Sub
Private Async Sub DelayExecute(action As Action, timeout As Integer)
Await Task.Delay(timeout)
action()
End Sub
End Class
Concretely in your case, your first txtTest_TextChanged starts a stopwatch. Your second txtTest_TextChanged calls _sw.Start() again, which has no effect on a running stopwatch:
Starting a Stopwatch that is already running does not change the timer state or reset the elapsed time properties.
When the first txtTest_TextChanged's continuation runs, the stopwatch's elapsed time is expected to be greater than a second: it was started more than a second ago, and since then, all that happened is that other attempts were made to start the same stopwatch. Nothing was reset.
That said, using a stopwatch here is inherently unreliable and I do not recommend continuing down this path. You cannot be sure exactly when your continuation runs.
Instead, do not measure whether your continuation should probably be cancelled, track whether it was cancelled.
The most direct way in your particular case would be to increment a counter in txtTest_TextChanged. If the counter has not been changed by the time the continuation is executed, you know txtTest_TextChanged hasn't been called a second time.
A more general way is to use the CancellationTokenSource class. Most task-based methods, including Task.Delay, have overloads accepting CancellationToken instances. You can indicate a request for cancellation through CancellationTokenSource.Cancel.
Although you do not need it in this case, in general, you can also call CancellationToken.ThrowIfCancellationRequested explicitly in specific locations during long-running operations that would not otherwise be aborted.

Invalid procedure call or argument

m getting an error while using
Text1.SetFocus
the error is
invalid procedure call or argument
If you're calling this from a module, i.e. not from the form code, you need to reference the form object where text1 lays.
The other thing you may need to do is to get some persistency pills, hit F1 more often and use words in abundance when asking for help.
You need to reference Text1.SetFocus from Form_Activate and no from Form_Load -
http://www.vb6.us/tutorials/understanding-forms-vb6-tutorial
Form_Load vs. Form_Activate
In the Form_Load event, you would typically perform initialization-type tasks, as you should. However, certain types of actions cannot be performed in the Load event, due to the fact that the form is fully loaded only after the Load event completes. For one thing, printing to the form will not work when done in the Load event. In addition, if you try to set focus to a particular control on the form during the Load event, you will get the message Run-time error '5': Invalid procedure call or argument. For example, assume you had a textbox called Text1 on the form. The following code would result in that error:
Private Sub Form_Load()
' other initialization stuff
Text1.SetFocus ' causes an error
End Sub
The reason for the error is that since the form is not fully loaded, neither are any of the controls on it – and you can't set focus to a control that is not yet available.
To remedy this problem, you should use one of the other Form events, such as the Activate event. (When VB loads a form, it actually cycles through a number of events, such as: Initialize, Load, Resize, Activate, GotFocus, and Paint. Of these, Load and Activate are probably the ones most commonly used. ) Placing the code to set focus to a control will work in the Form_Activate event:
Private Sub Form_Activate()
' other statements
Text1.SetFocus ' no problem here
End Sub
A caution about the activate event: it will fire whenever your application switches to that form. For example, if you switch back and forth between Form1 and Form2, be aware that any code you might have in the Activate events for these forms will be executed when you switch to that form. Therefore, if you have code in the Activate event that you only want to execute "the first time", you will need to control execution with a Boolean switch. For example, in the General Declarations of your form you could define the following variable:
Private mblnFormActivated As Boolean ' will be initialized to False by default
You can then use this switch in the Activate event as follows:
Private Sub Form_Activate()
If mblnFormActivated Then Exit Sub
' statements you only want to execute once, including the following
' statement to turn the switch on:
mblnFormActivated = True
End Sub

VB.NET - Passing an event as a parameter

I need to pass an event as a parameter to a function. Is there a way of doing this?
The reason is that I have a sequence of two lines of code that is littered all over my program, where I dynamically remove the handler to an event, and then set the handler again. I'm doing this for several different events and event handlers, so I've decided to write a function that does this.
As an example, let's say I have a combobox in my code called combobox1, and I have the handler called indexChangedHandler. In several places of my code, I have the following two lines:
RemoveHandler combobox1.SelectedIndexChanged, AddressOf indexChangedHandler
AddHandler combobox1.SelectedIndexChanged, AddressOf indexChangedHandler
Now, I don't want to keep on repeating the above two lines of code (or similar) all over my program, so I'm looking for a way to do this:
Private Sub setHandler(evt As Event, hndler As eventhandler)
RemoveHandler evt, hndler
AddHandler evt, hndler
End Sub
so that everywhere where those two lines of code(or similar) occur in my program, I can just replace them with:
setHandler(combobox1.SelectedIndexChanged, AddressOf indexChangedHandler)
So far, the "evt as Event" part of the argument of the setHandler function is giving an error.
P.S: I've asked this question on a couple of other forums and keep getting asked why I would want to set the handler immediately after removing it. The reason is because dynamically adding an event handler n-times causes the handler to be executed n-times when the event occurs. To avoid this, that is, to ensure that the handler is executed just once when the event occurs, I first remove the handler each time I want to add the handler dynamically.
You might be asking why the handler would be added several times in the first place... The reason is because I add the handler only after a particular event, say E1, in my form has occurred (I add the handler within the handler of event E1). And event E1 can occur several times within my form. If I do not remove the handler each time before adding it again, the handler gets added and thus executed several times.
Whatever the case, the processing occurring within the function is not of ultimate importance to me at this time, but rather just the means of passing an event as a parameter.
Of course you can pass events around... Well you can pass Action(Of EventHandler) which can do what you want.
If you have a class that defines an event like so:
Public Class ComboBox
Public Event SelectedIndexChanged As EventHandler
End Class
Given an instance of ComboBox you can then create add & remove handler actions like so:
Dim combobox1 = New ComboBox()
Dim ah As Action(Of EventHandler)
= Sub (h) AddHandler combobox1.SelectedIndexChanged, h
Dim rh As Action(Of EventHandler)
= Sub (h) RemoveHandler combobox1.SelectedIndexChanged, h
(Now, this is VB.NET 4.0 code, but you can do this in 3.5 using AddressOf and a little more mucking about.)
So if I have a handler Foo:
Public Sub Foo(ByVal sender as Object, ByVal e As EventArgs)
Console.WriteLine("Over here with Foo!")
End Sub
And a Raise method on ComboBox I can now do this:
ah(AddressOf Foo)
combobox1.Raise()
rh(AddressOf Foo)
This writes the message "Over here with Foo!" as expected.
I can also create this method:
Public Sub PassActionOfEventHandler(ByVal h As Action(Of EventHandler))
h(AddressOf Foo)
End Sub
I can pass around the event handler actions like so:
PassActionOfEventHandler(ah)
combobox1.Raise()
PassActionOfEventHandler(rh)
Which again writes the message "Over here with Foo!".
Now, one issue that might be a problem is that you can accidentally swap the add and remove event handler delegates in code - after all they are the same type. So it is easy to just define strongly-typed delegates for the add and remove actions like so:
Public Delegate Sub AddHandlerDelegate(Of T)(ByVal eh as T)
Public Delegate Sub RemoveHandlerDelegate(Of T)(ByVal eh as T)
The code to define the delegate instances doesn't change except for the delegate types:
Dim ah As AddHandlerDelegate(Of EventHandler)
= Sub (h) AddHandler combobox1.SelectedIndexChanged, h
Dim rh As RemoveHandlerDelegate(Of EventHandler)
= Sub (h) RemoveHandler combobox1.SelectedIndexChanged, h
So this now lets you be very creative. You can define a function that will take the add handler delegate, the remove handler delegate and a event handler, which will wire-up an event handler, and then return to you an IDisposable that you can use later to remove the handler without needing to retain a reference to the event handler. This is handy for using Using statements.
Here's the signature:
Function SubscribeToEventHandler(
ByVal h as EventHandler,
ByVal ah As AddHandlerDelegate(Of EventHandler),
ByVal rh As RemoveHandlerDelegate(Of EventHandler)) As IDisposable
So given this function I can now do this:
combobox1.Raise()
Using subscription = SubscribeToEventHandler(AddressOf Foo, ah, rh)
combobox1.Raise()
combobox1.Raise()
End Using
combobox1.Raise()
And this writes the message "Over here with Foo!" only twice. The first and last Raise calls are outside of the subscription to the event handler.
Enjoy!
You cannot pass events around. Event isn't a type, it's a keyword that defines a pair of methods, add and remove, used to change the state of the event member of the class. They are very much like properties in this respect (which have get and set methods).
Like properties, the add and remove methods can do whatever you want. Typically, these will do nothing more than maintain a delegate instance, which itself is a MulticastDelegate or in other words, a list of delegates which are getting called one by one if the event is raised.
You can clearly see this structure in C#, where it is not masked with AddHandler/RemoveHandler, but you directly edit the list of associated handlers: myObject.Event += new Delegate(...);.
And, again like properties, being a member of a class that actually abstracts two different methods, it's not possible to literally pass an event as an object.
There are a number of different meanings for the term "event", depending upon context. In the context you are seeking, an Event is a matched pair of methods that will effectively add or remove a delegate from a subscription list. Unfortunately, there's no class in VB.NET to represent a method address without an attached object. One could probably use reflection to fetch the appropriate methods, and then pass those methods to a routine that would call them both, but in your particular situation that would probably be silly.
The only situation where I can see that it might be useful to pass an event in the sense you describe would be for something like an IDisposable object which subscribes to events from longer-lived objects, and which needs to unsubscribe all of its events when it is disposed. In that case, it may be helpful to use reflection to fetch the remove-delegate method for each event, and then call all of the remove-delegate methods when an object is disposed. Unfortunately, I know of no way to represent the events to be retrieved except as string literals, whose validity could not be checked until run-time.