My.Application.MainWindow is Nothing - vb.net

After moving MainWindow.xaml in VB project using the Visual Studio into project folder Windows\MainWindow.xaml I've got some trouble (broken references etc.). I needed to re-create MainWindow.xaml to get them resolved (it was longer time ago, I don't remember exactly).
Currently, variable My.Application.MainWindow contains Nothing during runtime.
I've compared the project against blank project where My.Application.MainWindow contains correct reference during the runtime and found no place in original project where setting of My.Application.MainWindow is omitted (or something similar).
Do you have any experience on which place My.Application.MainWindow is being initialized in VisualStudio 2012 project?
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) Handles Me.Startup
'next line throws NullReferenceException
Debug.Print("My.Application.MainWindow.Name = " & My.Application.MainWindow.Name)
'some other code here...
End Sub

OK, it seems that My.Application.MainWindow points to main window object only if main window is open. It is Nothing otherwise. So I had two issues:
In one of paths of my original code, I was accidentally closing main window, so My.Application.MainWindow became Nothing after calling Close()
In code shown in the question, it was too early to check for My.Application.MainWindow value – it was Nothing because the main window was not opened yet

Related

Why does my form look so different after publish vs release?

I've went to publish my first vb.net windows form and was surprised the format I meticulously combed over became all skewed after publishing.
Why did the controls change to older style '3d' and the overall ratio of the form stretched in the horizontal? My calendar date pickers also changed format.
Is there a way to make the published form look exactly like the release version, down to the pixel?
For anyone experiencing appearance issues, I can share that in my case, this seems to be related to my project starting first in visual studio 2019 and then I changed over VS 2022. I am happy to report that as soon as I copied my code over to a clean project in 2022, everything works great! The published copy looks completely identical to the release/debug version and I didn’t need to play with any settings in the Main Sub!
Thank you djv for working with me!
You can control visual styles before you create your UI thread, but VB.Net will enable visual styles for you in Sub Main, which is inaccessible to you! You can get around this by creating your own Sub Main, but you also need to choose this new method as the entry point to your application.
' in a new class file, I called Program.vb
Public Module Program
<STAThread>
Public Sub Main()
Application.VisualStyleState = VisualStyles.VisualStyleState.NonClientAreaEnabled
Application.Run(New Form1())
End Sub
End Module
In the project properties, click Startup object, choose Program
My Form1 has two TextBoxes. Here's the code
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TextBox1.BorderStyle = BorderStyle.FixedSingle
Me.TextBox2.BorderStyle = BorderStyle.Fixed3D
Me.FormBorderStyle = FormBorderStyle.FixedSingle
End Sub
End Class
and here is the result
Note with Application.EnableVisualStyles() instead, I'm getting all single borders.
Hope some setting of visual styles does the trick

Migrating a program from VB2015 to VB2019 - program won't start

I wrote a Visual Basic program back in VB4 (yes, really!) to track my petrol/gas consumption, and subsequently compiled it in VB6, Visual Studio Express 2010 (I think), VS Express 2015 for desktop, and I'm now trying to compile it in VS 2019 Community, without success.
I made a back-up copy of the source code folders, and pointed VB at the original .sln file. The source all seemed to load up ok, but when I try to run the program in debug mode, the splash screen comes up, but never goes away, and the main form "frmMain" never gets loaded. I set a breakpoint at the first line of code in frmMain:
Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
but I get an error "The breakpoint will never be hit. No symbols have been loaded for the current document".
This doesn't mean anything to me, and this message has appeared in the forums for years, seeking explanation, without an agreed common solution. I'm definitely in 'Debug' mode, not 'Release'. I've checked in Properties/Application that frmMain is the Startup form, and the Splash screen is set to frmSplash. Is the 'current document' frmMain? What are 'Symbols'?
Incidentally, I have a lot of 'Messages' which say, eg 'Message IDE1006 Naming rule violation: These words must begin with upper case characters: btnSaveNewCar_Click'. Why is this? It's never arisen before - has something changed in VB?

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.

Form.Load event not firing, form showing

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.

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.