Form.Load event not firing, form showing - vb.net

I fear that there is something obviously wrong with my code, but I have come across a situation where the Form.Load event is not firing when I create and show my form.
The form is not subclassed (as I've seen some problems with that in some searches), and I am not getting any errors thrown when I step through the code in the debugger.
I have a break point set on the IDE-created form load function (which does have the Handles MyBase.Load signature suffix) but the breakpoint is never reached and the form does display and work.
The form is passed three arguments in the constructor but the IntializeComponent() function is called before anything else is done.
Code:
Public Sub New(ByVal argA As Object, ByVal argB As Object, ByVal mode As FormMode)
' This call is required by the Windows Form Designer.
InitializeComponent()
' Other code here,
' No errors generated
'
End Sub
The form load function is as follows, (but this is never actually executed as the event is not fired).
Code:
Private Sub frmInstrumentEditor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not argA Is Nothing Then ' argA set in constructor
' Operations using argA
End If
End Sub
I might add I am using some databinding with some controls and the argA object, but if this was producing an error I thought I would have seen this (I have CLR Execpetions settings set to Thown in the debugger > exceptions window)
Any ideas why this might be occurring?

I just had a similar issue (it was in Shown event, not Load, but the root cause is the same). The reason was hidden deep in one of the ancestors - there was an unhandled NullReferenceException thrown and this exception was somehow "muted".
I found it after extensive debugging with F11.
But... when writing this answer I found this post on SO
Just add Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in your Main() method.
If you're using a 64-bit machine, it provides you with the solution (it worked in my case, too).

I had a similar problem. On opening the form for the first time, the load event would not be tiggered but on opening it the second time, all would be well. The problem tuned out to be one of my text boxes which was bound to a field that I had deleted from the database (sql server - I was using datasets, tableadaptors and bindingsources in a fairly standard way).
Make sure that all the controls on your form that are databound have fields that exist in the dataset and that the dataset is an accurate reflection of the underlying database table (the easiest was to do this last bit is to use the "Configure data source with wizzard" button on the data sources window (menu -data - show data sources) and remove the table. Then use it again to add the table back- this should make sure all the data matches.
Hope this helps.

OK I had the SAME problem (I think) and the clues here helped. It was databinding (sort of)
I had properties of some controls bound to settings and when I delete these settings the form load event stopped running. Removed the bindings and now it is running again.

Here is another idea.
What happens if you set all exception types (not just for the CLR) to be thrown instead of user-unhandled. Does the application break anywhere at all?
Also, just to double check, you are in debug mode right?

The problem you are experiencing may be caused by the application needing to fully load the form before you can do the "other code." This could be due to the other code dealing with objects on the form that haven't finished loading. You could use a timer that gets enabled in the load function to execute the other code. This way you don't have any timing issues and you can first load the form, and then a split second later, run the code you want from the timer.

Is your windows form inheriting from a base page? If so, the base page probably also has a Form Load event handler. In that base page Form Load event handler you will probably find an exception that is being thrown. So it is exiting the base page form load event handler and not firing the form load event handler in your inherited windows form.

I had a similar issue, the problem was a mistake in the databinding. Omit the code for databinding and give it a try. I think the load event handler will be hit. Then see what's wrong with the databinding part.

Had the same problem. Checked my data bindings, everything looked ok. Got to thinking, even though form was closed, maybe .NET wasn't sure (old days, sometimes forms were only hidden and not really closed).
I added the event handler FormClosed and put a single line in it:
Private Sub frmScheduleInquiry_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Dispose()
End Sub
Problem solved!

Solved....
Have spent 4 hours and finally got clues from this answers.
in my case i was having couple of TextBox control on the form bound to a BindingSource with respective column, i still have that bindingsource on the form but what was happened that i deleted one column from underlying database table so on the form there is still one TextBox exist pointing to that column with bindingsource, in fact there is no column like that because i deleted !..... this lead Form.load event was not firing ........finally fixed..
thanks to all of you ..

I had the exact same problem just happen to me. Turns out I had added some ApplicationsSettings properties to a form TextBox control, but later wanted to delete them. I thought I had cleared everything out, but obviously I didn't - and this was what caused the Form_Load() (and maybe other events as well) to not fire. Deleting and then re-adding the offending TextBox did the trick.
Hope this helps

Matt is probably right about this one. Have you tried adjusting your code like this:
Private Sub frmInstrumentEditor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not argA Is Nothing Then ' argA set in constructor
' Operations using argA
Else
MessageBox.Show("argA has not been set")
End If
End Sub
If the messagebox appears it means that the event is fired before your argument is initialized. It would also account for the 'strange' behaviour concerning closing/opening the form.
Have you tried running the argA operations in the 'Shown' event?

Not sure if this will help, but I just ran into this issue because somebody mistakenly deleted the Handles Me.Load. I see you show MyBase.Load try changing it to Me.Load.

I had a similar issue. It turned out that I was not using the Show method on the form - instead using a user32.dll ShowWindow call. This means the form still appeared, but the Load event was never fired because the dotNet Show method was never called.

I know that this is an old post, but I thought that if someone was searching this issue, that my fix to this problem might help.
I was having this same problem as stated in the originally posted question, but I didn't have any data bound fields on the form. I found that the problem was in the fact that I was using the CurrentDeployment.CurrentVersion method and it was causing the silent problem. I set the application from debug mode to release and the problem still existed. Through trial and error I remarked out the defining method Dim xVersion As Version = ApplicationDeployment.CurrentDeployment.CurrentVersion
and presto... its now working as usual.
I ended up changing the orginal code the code below.
Dim xVersion As Version = ApplicationDeployment.CurrentDeployment.CurrentVersion
sysVersion = String.Format("{0}.{1}{2}.{3}", xVersion.Major, xVersion.Minor, xVersion.Build, xVersion.Revision)
New code
#If (DEBUG) Then
sysVersion = "[Debug mode]"
#Else
Dim xVersion As Version = ApplicationDeployment.CurrentDeployment.CurrentVersion
sysVersion = String.Format("{0}.{1}{2}.{3}", xVersion.Major, xVersion.Minor, xVersion.Build, xVersion.Revision)
#End If
I hope this helps someone.
Happy Coding...

Same problem, I rewrote the designer and that fixed it. The designer was loading then crashing (silently of course), and form_load was not firing due to that.

Had same issue, but cause was totally different.
Form was being shown using form.Show() instead of form.ShowDialog()

I experienced this symptom when building and running a .NET 4.0 WinForms application which loaded a series of older assemblies (.NET 2.0; .NET 1.1).
In the past I had seen this cause a mixed-mode assembly exception. In this particular case, the main Form loaded without exception and without executing any of its Form Load code.
The solution, in my case, was to set useLegacyV2RuntimeActivationPolicy="true" in the App.config document.
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

Make sure your "Solution Configuration" box at the top of your IDE is showing "Debug".
I found that if it showed "Release" the "Load" method was not captured by the debugger.

In my case, the main form had WindowState: Maximized set in the designer. This was causing the window to be drawn on screen prior to the Load event firing.

Related

vbnet 2008 forms.designer.vb undo bug

I'm having this InvalidOperationException
An error occurred creating the form. See Exception.InnerException for
details. The error is: Object reference not set to an instance of an
object.
pointing at this line of code:
Private Sub BeginningBalancesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BeginningBalancesToolStripMenuItem.Click
inventory.MdiParent = Me <--error here
inventory.Show()
End Sub
EDIT:
Im only using drag and drop for creating controls from the toolbox. The thing here is, everything works fine until I relocated AND decided to return panel_001 to its previous location by pressing ctrl-z in the inventory.vb during design time to revert the change I made. The program runs fine without error prior to that specific panel relocation. I never edited any codes in the designer.vb and in the inventory class. I strongly believe that a piece of code wasn't properly restored at the ctrl-z action in the inventory.Designer.vb. Is this a visual studio bug?
EDIT: I tried creating a new winform and attempted to start fresh by foolishly copying & pasting all the controls and the forms' class and was no good. I assume the problem does not lie under the striked-out line above.
The Winforms designer has a knack for tripping really mystifying design-time exceptions. A side-effect from its strong WYSIWYG design, it will run some event handlers at design-time. Like Paint, making a control look the way it does at runtime. Nice, but that does come with a price. This can easily cause an exception if such an event handler was not written to operate correctly at design time. You are supposed to use the DesignMode property to keep the code safe.
Coming up with a way a Click event handler could run at design-time however requires massive amounts of imagination. That is an event that will not run at design time, the designer uses a layered window that intercepts any mouse clicks, using them for design use instead. Like selecting a control or displaying the design-time context menu.
I have actually seen the Click event of a ToolStripMenuItem run. The designer is not 100% watertight but it happened just once and I was hacking the code pretty hard. Coming up with a way that it could possibly run by using Undo is going to be difficult. Maybe you give it the Ctrl+Z shortcut, don't assume that guess is credible.
The way to deal with incomprehensible black magic like this is to just dismiss it and move on with your life. You just don't stand much of a chance to diagnose it and if you do then there's nothing you can do about it anyway because this isn't your code. Well, other than the need to use DesignMode, that may well be necessary. Not in this case. The only thing you have to watch out for is that such an exception did not destroy the InitializeComponent() method. That can happen too, you notice by controls being missing when you re-open the designer. Very unpleasant, you do need a good backup copy in source control to recover from that lossage.
OK! after giving it a few more tries, I found the answer. After the exception shows, copy exception details to clipboard and then I pasted it on Notepad. It had a lot of texts but the bottom part was the important one:
--insert wall of texts here-- in C:\Users\Ellen\Documents\Visual Studio
2008\Projects\SampleApplication\SampleApplication\Forms\inventory.Designer.vb:line
760 at CabuyaoWaterDist.inventory..ctor() InnerException:
It pointed me out to the specific line in the designer where the ctrl-z did not properly revert one of the label's caption

What causes Visual Studio To Change Control Names?

In one project, the names of my GUI controls are being changed at compile time.
Say, for example, I have a Label control named **lblRow0Col1".
I noticed my code was failing to find the control by name:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each ctrl As Control In Controls ' .Find("Label*", False)
If ctrl.Name = "lblRow0Col1" Then
ctrl.Text = DateTime.Now.ToShortDateString()
End If
Next
End Sub
So, I stepped through that routine and found the control I needed had been renamed to what looks like a GUI string.
lbl.Name = "07178f89-6fdd-47c7-9f84-d4d661df7554"
I created a test project to see what was going on, but this is not happening in the test project.
Is there a VS setting that tells the compiler to scramble the control names?
How do I stop this behavior?
OK, I’ve been looking at the code for that routine that populates a "details view" screen.
Before, I was filling the detail screen as soon as the Inventory Item variable changed.
I got to thinking that people rarely view the details screen, so why not just populate it after the screen was displayed? I had an event for “after displayed”, so I moved it there.
Well, I just moved it back ...and the odd behavior went away.
I don’t know what the issue was that caused that to happen, though.
The Label controls should have already been generated, but it acts like they were not until the tab screen they were on was selected.
So, there's an answer, but I'd rather someone explain to me what I did wrong.

Why does my form appear behind everything?

I have a program where I need to do some initial work before calling the form, so I disabled the Application Framework setting and wrote my own Main function with a call to Application.Run(myForm) when it's time to run the form.
Everything was working fine, no problems, but now I have need of some other service before opening the form. Rather than add all that code to this program, it has all been moved into its own executable. This second program can edit files that the first program will use, so I need the first program to wait so that it will read up those changes (should they be made). I suppose could just as easily use the Shell function, but for various reasons I'm creating my own Process object and calling it/waiting on it through that.
Anyway, I make this call to the second program some time before the Application.Run call. The first program waits its turn, and I can interact with the second program successfully, no trouble at all. But when it's done, the window for the first program is hidden behind any other windows that are on the screen. This doesn't happen in XP, only in Vista (and maybe 7, but I haven't confirmed yet). I've already tried manually forcing the form to appear in front, minimize then maximize, get focus, etc, but nothing brings it to the front unless the user manually clicks on it with the mouse.
What am I doing wrong? Why does this behavior occur? I know it has something to do with waiting for the executable to finish, because if I don't force the first program to wait everything is fine (other than it not waiting). I can circumvent the issue by calling the second program in the Load event of the form, but then I have to read the file a second time to catch the changes instead of reading it once, and it also looks bad because the form is being drawn really slowly while the second program is sitting there.
If anyone has any input, I'd appreciate it.
This isn't really an answer to why you're experiencing this behaviour, but a simple workaround would be to temporarily set the form's TopMost property to True in the load event. Then, depending on how intrusive you want that to be, you could either reset it under a short timer or wait for say the MouseEnter event to fire.
There are another topic in this site about that, but I not got the link. This problem seems be a bug into .NET framework. The API below (VB.NET example) works for me in windows XP and 8.1. Don't tested in other versions of Windows.
<Runtime.InteropServices.DllImport("user32")> _
Public Shared Function SetForegroundWindow(hwnd As IntPtr) As Integer
End Function
Private Sub Form_Load(sender As Object, e As EventArgs) Handles Me.Load
SetForegroundWindow(Handle)
End Sub

VB.NET 2005 problems with Designer not being able to process a code line

I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the "FitTrack"? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors...
The error is:
Warning 1 The designer cannot process the code at line 27:
Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11
The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0
I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form.
I would take out the static assignment in the designer to the resource CrystalReport11 and then add a load handler to your form and before setting the ReportSource back to CrystalReport11 do a check
If(Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11
Here is a mockup..
Public Sub New()
InitializeComponent()
AddHandler Me.Load, New EventHandler(AddressOf Form1_Load)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
If (Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11
End Sub
You should be able to take a backup, clear the lines that are having problems then when you re-open it the designer will fix the code.
The key is that you want to let the designer re-generate, then just validate that all needed lines are there.
That usually works for me, but you just have to be sure to remove all lines that it doesn't like.
I do an easy way; Right Click on the report then choose Run Custom Tool.
Automatically it fixes all problems and working for me, i solve 52 crystal ReportViewer errors.

Force multi-threaded VB.NET class to display results on a single form

I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.
I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.
Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.
MORE INFORMATION: I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?
I'm going to pull my hair out! This can't be that hard!
SOLUTION: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:
Public Sub New()
If My.Application.OpenForms(0).Equals(Me) Then
Me.IsFirstForm = True
End If
End Sub
Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):
Public Sub EventHandler()
If Not IsFirstForm Then
Dim f As Form1 = My.Application.OpenForms(0)
f.EventHandler()
Me.Close()
ElseIf InvokeRequired Then
Me.Invoke(New HandlerDelegate(AddressOf EventHandler))
Else
' Do your event handling code '
End If
End Sub
First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!
Again, thanks for all the help - this was going to drive me nuts!
I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.
Edit after OP changed question:
A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a new instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.
You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms:
Dim main As Form1 = CType(Application.OpenForms(0), Form1)
if (main.InvokeRequired)
' etc...
Use Control.InvokeRequired to determine if you're on the proper thread, then use Control.Invoke if you're not.
You should look at the documentation for the Invoke method on the Form. It will allow you to make the code that updates the form run on the thread that owns the form, (which it must do, Windows forms are not thread safe).
Something like
Private Delegate Sub UpdateStatusDelegate(ByVal newStatus as String)
Public sub UpdateStatus(ByVal newStatus as String)
If Me.InvokeRequired Then
Dim d As New UpdateStatusDelegate(AddressOf UpdateStatus)
Me.Invoke(d,new Object() {newStatus})
Else
'Update the form status
End If
If you provide some sample code I would be happy to provide a more tailored example.
Edit after OP said they are using InvokeRequired.
Before calling InvokeRequired, check that the form handle has been created, there is a HandleCreated property I belive. InvokeRequired always returns false if the control doesn't currently have a handle, this would then mean the code is not thread safe even though you have done the right thing to make it so. Update your question when you find out. Some sample code would be helpful too.
in c# it looks like this:
private EventHandler StatusHandler = new EventHandler(eventHandlerCode)
void eventHandlerCode(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(StatusHandler, sender, e);
}
else
{
//do work
}
}