When I call an pre-existing event handler from a subroutine, it doesn't come back. VB - vb.net

I'm looking to call a pre-existing event handler subroutine from the form_Load event handler.
But the below doesn't work because control doesn't come back and I want to do more.
UPDATE:
I'm new to this so I don't know what the proper protocol is but...
The reason for the non-return was that a statement like the below ended the subroutines execution.
If aLabel.Tag = 1...
the fix was adding New to the declaration to create an instance of it, ie..
changing....
Dim aLabel As Label
... to ...
Dim aLabel As New Label
I'm surprised I didn't get a warning but instead they just abruptly stopped execution of the sub. That wasn't very helpful :)
Thanks again for your time guys...
(Maybe this question should be deleted now that it has served its purpose)
#konrad #karl
END OF UPDATE
What doesn't work is....
Private Sub Form1_Load...
button1_Click(sender, e) 'But Control doesn't come back.
end sub
Do I change the sender to something?
Thanks in advance
Dave

Invoking event handlers like this is a bad idea, because you are trying to simulate the event context by making sender and/or EventArgs be something else.
Instead, put the logic that you want to invoke into a Subroutine or Function and have your Form1_Load method call that; likewise if you really do have a real click event handler, then that handler code can call the method too, like this:
Private Sub Form1_Load()
DoSomeWork()
End Sub
Protected Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
DoSomeWork()
End Sub
Private Sub DoSomeWork()
' Put logic here that you want to do from form load and a button click
End Sub
This has the benefit of making the code cleaner, clearer and easier to maintain as you only need to change the logic in one place should you need to change the logic.
Note: Obviously, you can pass parameters to the DoSomeWork method, if need be, and change it to a Function if you need it to return something.

Related

Why does my subroutine, which handles a double-click event on a listbox, not work?

I have declared a Sub that is meant to trigger when the listbox 'lstStudents' is double-clicked. However, it does not trigger when this happened. There can't be an error in the code itself as it is auto-generated. Why does the code not function as expected? The code is below:
Private Sub lstStudents_DoubleClick(sender As Object, e As EventArgs) Handles lstStudents.DoubleClick
Msgbox("test")
End Sub
The message box is only present for testing purposes.
Could You try to delete that previous "lstStudents" and add new one then apply the "ListBox1_DoubleClick" on it again to make sure it works.
Otherwise let us know what is going there because I think your code is normally and it should be working 100%.

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.

VB.Net Multi-Threading InvokeRequired and Passing Thread

I need to be able to pass the thread name into a subroutine in order to abort it when I need to.
So I have this so far:
Dim BrowserSpawn As New System.Threading.Thread(AddressOf BrowserSub)
BrowserSpawn.Start()
Private Async Sub BrowserSub(BrowserSpawn)
...
End Sub
Because the subroutine creates a browser within Form1 groups I needed to invoke access to these controls within the sub.
Note: This works fine when I'm not passing in the thread name.
If Me.GroupNamehere.InvokeRequired Then
Me.GroupNamehere.Invoke(New MethodInvoker(AddressOf BrowserSub))
Else
'Do nothing
End If
When I'm passing in the thread name these become a problem when trying to compile:
Method does not have a signature compatible with delegate 'Delegate Sub MethodInvoker()'.
I'm hoping this is just a syntax thing but I can't seem to get it to work. Is there any way I'm able to pass in this thread name without breaking my invokerequired check?
If I try and change it to the obvious:
Me.GroupNamehere.Invoke(New MethodInvoker(AddressOf BrowserSub(BrowserSpawn)))
It tells me Addressof operand must be the name of a method (without parentheses). Although without the parentheses it's not happy either so I don't know where to go from here.
/edit:
Stumbled across How can I create a new thread AddressOf a function with parameters in VB?
Which seems to confirm what I was trying passing something like:
Private Sub test2(Threadname As Thread)
' Do something
End Sub
And the sub seems happy with that. But I'm not sure how to do that without breaking the invoker part.
Me.GroupNameHere.Invoke(New MethodInvoker(AddressOf SubNameHere))
Works normally. If SubNameHere() becomes SubNameHere(threadname as thread) then that seems happy enough but the invoke line breaks and doesn't want more than the address of.
Two slight syntax changes sorted it:
Private Async Sub SubName(ThreadNameAs Thread)
and
GroupName.Invoke(New MethodInvoker(Sub() Me.SubName(ThreadName)))

How Can I RaiseEvent Manually For A FileSystemWatcher

I have extended on the FileSystemWatcher class to incorporate a FolderCount monitor and FolderEmpty monitor that raise events if a folder reaches a specified amount of files or if a folder returns to an empty status. I seem to have this working and I'm getting events raised when these conditions occur.
However, my problem is that when my FileSystemWatcher first initializes, it automatically goes in to check the folder contents of the specified folder to get a file count. If the limit is already reached, I need to raise an event immediately rather than wait for the FileSystemWatcher to report it.
Currently I can only seem to raise events by plugging into the .Created and .Deleted calls, however, because no files are getting created or deleted, I don't know how to raise my event manually.
Public Sub Initialize()
SetFolderCountStatus() 'Set the isFolderEmpty flag based on file contents
If Not isFolderEmpty Then
If options.WatchForFolderCount Then
If FileCountReached(options.FileCountToWatch) Then
RaiseEvent EventFolderCount(sender, e) 'Sender and e are never defined
End If
End If
End If
End Sub
My problem is that both sender and e are never populated with anything because they sit outside of my WatcherEventArgs.
I'm sure this can be done a better way, but I am unsure. Any help would be appreciated. Thanks
Do you actually use the sender and EventArgs in your EventFolderCount method? You can pass Me for the sender and an empty EventArgs object.
However What are the event arguments “sender” and “e” suggests attempting to raise the event isn't preferred. Instead you should have a single method that accomplishes the task and have that called in both places.
I actually resolved this by changing my EventHandler to only require a String variable, rather than EventArgs:
Public Event EventFolderCount(filename As String)
This way I could call it easily inside and outside of the FileSystemWatcher like so:
RaiseEvent EventFolderCount(filename)
Thanks #Dave Anderson for pointing me in the right direction.

Visual Basic - how to force event to fire

I'm new to VB (using VBA, actually) and I would like to force an event to fire. Specifically, I am updating the value in a textbox and I would like to call that textbox's AfterUpdate() event.
Private Sub cmdCreateInvoice_Click()
Me.txtInvDate = '11/01/10'
Me.txtInvDate.AfterUpdate
End Sub
During run time, I get an error that says "Compile Error: Invalid Use of Property". If I try something similar, but with the click event (ex: cmdCreateInvoice.Click), which does NOT have a property that shares the name, I get an error that says "Compile Error: Method or Data member not found".
I know there must be a way to fire one event from another. But what is the proper syntax?
Thanks!
AFAIK, there is no way to "fire an event manually" in VB(A). What you can do is call the event handler manually, and for this, rdkleine has given you the answer already:
Call txtInvDate_AfterUpdate()
This will have exactly the same effect as if the event had fired (though it does not give you the whole chain of events that may also fire along with it--unless you Call their handlers as well).
IgorM has another valid point, in comments on his answer--it's "cleaner" to write a different Sub to do the work you want done, then call it from both the event handler & wherever you're trying to do it now (button click?). So:
Private Sub txtInvDate_AfterUpdate()
DoWhatever
End Sub
Private Sub button_Click()
DoWhatever
End Sub
Private Sub DoWhatever
'your desired effect
End Sub
You could even make DoWhatever a Public Sub in a Module.
Edit
And no, in VB(A) it doesn't matter what order you define your Sub (or Function) routines.
Call
txtInvDate_AfterUpdate()
Try to use something like this:
Private Sub TextBox1_LostFocus()
TextBox1.Value = "5"
End Sub
Use LostFocus event if you change value manually.
Or you can use another way:
Private Sub CommandButton1_Click()
TextBox1.Value = "new value"
End Sub
Private Sub TextBox1_Change()
MsgBox TextBox1.Value
End Sub
Try to use Change event.
Some code apparently will (regretfully) force events to fire:
Me.Dirty = False
forces BeforeUpdate and AfterUpdate to fire, as I understand it. There are probably more cases too. Any secret hooks which attach to your code in that manner reflect bad design in my view and will inevitably lead to inadvertant & frustrating loops being created.
Is there a way to keep a textboxes event firing until I click on another text box? I'm needing to stay "in" the text box which has Do While loop for a selection. Once the selection is made, I want the user to be able to replace the selection without having to click on the text box again. If the user is satisfied with the select, they can click on a different text box.