Why is this CInt function call *not* throwing an error? - vb.net

I'm just curious, really.
There was some code that wasn't handling empty strings before converting, essentially calling
Dim StringToConvert As String = ""
Dim a As Integer = CInt(StringToConvert)
Rather then something like
Dim StringToConvert As String = ""
Dim a As Integer = CInt("0" & StringToConvert)
and so it makes sense that it would throw an error...
What I don't understand is that this wasn't throwing an error on my machine when I was debugging. But it does throw an error when compiled!
Here is what calls the CInt function and only sometimes throws an error:
Public NotInheritable Class SomeForm
Inherits Windows.Forms.Form
Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles TextBox.LostFocus
StaticHolderClass.StaticMethod(DirectCast(sender,TextBoxBase))
End Sub
End Class
Public NotInheritable Class StaticHolderClass
Public Shared Sub StaticMethod(ByVal sender As Windows.Forms.TextBoxBase)
sender.Text = Format(CInt(sender.Text),"#,#")
End Sub
End Class
Does anyone know why this would happen?

In VB, occasionally when an error is encountered during form initialization, it doesn't get reported properly. Sometimes the error is not flagged at all, and sometimes it appears to be from a different location. For example, in the following code (on my system), an error is thrown with the button click and not the form load:
Public Class Form1
Dim k As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
k = CInt("")
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
k = CInt("")
End Sub
End Class
It seems to depend on the environment, so "your results may vary". You can work around this sometimes by using the shown event rather than load.

Related

{A first chance exception of type 'System.NullReferenceException' occurred in calculator.exe} error during declaring variable

How to write this code in a right way?
Public Class Form1
Dim y As String = lbl_1.Text
It says:
{A first chance exception of type 'System.NullReferenceException' occurred in calculator.exe}
Can you help me guys?
this is a sample from the code
Public Class Form1
Dim y As String = lbl_1.Text
Private Sub btn_diff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_diff.Click
lbl_1.Text = y & "-*"
End Sub
Private Sub btn_1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_1.Click
lbl_1.Text = y & "1"
End Sub
Private Sub lbl_1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbl_1.Click
Dim y As String = lbl_1.Text
lbl_1.Text = y
End Sub
Private Sub btn_n_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_n.Click
lbl_1.Text = ""
lbl_1.Focus()
End Sub
Private Sub btn_2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_2.Click
Dim y As String = lbl_1.Text
lbl_1.Text = y & "2"
End Sub
Private Sub btn_equal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_equal.Click
lbl_1.Text = Val(lbl_1.Text)
End Sub
End Class
i want to make a calculator
but what should i write in the last button (btn_equal)? i have tried val but it doesnt work as i want
also when i declare y in each conrol it works but in puplic it doesnt work
The controls in the class Form1 need to be initialized before being used. If you want to use a control in that way you need to explicitly add the parameterless constructor to Form1 class
Public Class Form1
Dim y as String
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
y = lbl_1.Text
....
End Sub
End Class
In your actual code, the reading of the label control's text happens before the label itself has been created in the InitializeComponent hidden call. If you declare explicitly the parameterless constructor (Public Sub New()) then the VS IDE adds the call to the InitializeComponent and you could place the initialization of your string variable after the creation of the label.
(You could find the InitializeComponent method inside the Form1.Designer.vb file if you click Show All Files in the properties window)
For future knowledge consider to read this QA where cases of NullReferenceException are discussed thoroughly.

Read/Compile vb.net code dynamically from text file

I am trying to read and compile code from a text file. I have done some of its portion but feeling difficulties when trying to add controls to the Form. Kindly guide me. I am attaching code.
Public Class Form1
Sub Execute()
' Creates object of the compiler
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
'References/Parameters.
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
'Compiles in memory.
objCompilerParameters.GenerateInMemory = True
'Runs the source code.
'You can use resources, textbox's or even the settings, up to you! :D
'Dim strCode As String = TextBox1.Text
'Compiler Results
'Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromFile(objCompilerParameters, "H:\VB project\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\file.txt")
'If an Error occurs
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
'Creates assembly
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
'Trys to excute
Try
objTheClass.GetType.InvokeMember("ExecuteCode",
System.Reflection.BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Runs the source code from textbox1.
Execute()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As New Form2
p.Text = "hahahahah"
p.Show()
End Sub
End Class
"Type Form2 is not defined"
That's because you haven't defined it. You may be dynamically loading and compiling some file which contains code which does define it. But the compiler has no way of knowing that at compile time. Being a statically typed system, the compiler needs to know about all of the types you're using when it compiles the code.
If you're dynamically loading class definitions from a file, then you also need to dynamically invoke those class definitions. That's going to involve a lot of reflection and CodeDOM and whatnot. It's not going to be pretty, and it's definitely not going to have compile-time type checking. (And it's going to be very "stringly typed" in the sense that instead of creating an instance of Form2 you're going to be requesting from reflection to create an instance of "Form2" and hoping for the best.) So you're going to want to put in a lot of error handling for things like, for example, classes which don't exist.

Getting an object reference error in VB.net

Curious as to why I'm getting this error when attempting to debug my program in VB.net
Object Reference not set to an instance of the object.
It says that I am receiving this error due to lines 4 and 5:
Public Class Form1
Dim tSize
Dim S1 As String = ComboBox1.Text
Dim S2 As String = ComboBox2.Text
Private Sub FitContents()
tSize = TextRenderer.MeasureText(TextBox3.Text, TextBox3.Font)
TextBox3.Width = tSize.Width + 10
TextBox3.Height = tSize.Height
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = S1
TextBox2.Text = S2
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
Call FitContents()
End Sub
End Class
I would be extremely grateful if somebody were to explain why I am receiving this error.
Class level variables like S1 and S2 are initialized very early in the object construction process. Your visual controls, like Combobox1 and Combobox2, are not created until the InitializeComponent() method is called, which is not until almost at the end of the constructor.
Therefore, at the point when you try to set S1 to the value of Combobox1.Text, the Combobox1 object has not been created yet, and tring to reference a Null object's .Text property is going to give you that exception.
Instead, set those values at the end of your constructor, or in response to an event like Load.
You can also try building them as a property... like this:
Private Property S1() As String
Get
Return ComboBox1.Text
End Get
Set (ByVal value As String)
ComboBox1.Text = value
End Set
End Property

Stuck with an odd stack overflow

I'm writing this program in Visual Basic .NET to organize different fields of data, and I'm using profile slots through application settings to store the data for users. But, I ran into a stack overflow error in my SlotSelect.vb class. My best plausible guess for why this happens is that I'm using the wrong kind of variable container in the below sauce code, but my dilemma is that I don't know what specifically is going wrong.
The code that the vshost is saying is the cause for the overflow was written from some code that I looked up on MSDN and other places for referring to objects in other classes, and I tried using other variants of it to see if it was any different. So far, nothing has worked, and it doesn't stop the error while compiling, much less in the code markup--it only catches it when it starts the application in debug after it finishes building.
Here's the sauce code for SlotSelect.vb. Since most of the other unrelated classes (and this one) lead into MainForm.vb, I'll include its sauce too. The location vshost gave as the error is on the line where variable _MainForm is defined for Flaglister.MainForm to be used within SlotSelect.vb.
SlotSelect.vb
Public Class SlotSelect
' Class variables
Private _MainForm As Flaglister.MainForm = New Flaglister.MainForm
Private _SaveSlot As Flaglister.SaveSlot = New Flaglister.SaveSlot
Private _Misc As Flaglister.Misc = New Flaglister.Misc
Private _FlagsTextBox As System.Windows.Forms.TextBox = Flaglister.MainForm.FlagsTextBox
Private _VarsTextBox As System.Windows.Forms.TextBox = Flaglister.MainForm.VarsTextBox
Private _HackNameTextBox As System.Windows.Forms.TextBox = Flaglister.MainForm.HackNameTextBox
Private _RomCodeTextBox As System.Windows.Forms.TextBox = Flaglister.MainForm.RomCodeTextBox
Private _NotesTextBox As System.Windows.Forms.TextBox = Flaglister.MainForm.NotesTextBox
Private _ExpandedCheckBox As System.Windows.Forms.CheckBox = Flaglister.MainForm.ExpandedCheckBox
' Slot selection main execution subs
Friend Sub _0()
Try
' Disable FlagsTextBox
_FlagsTextBox.DeselectAll()
_FlagsTextBox.ClearUndo()
_FlagsTextBox.Clear()
_FlagsTextBox.Enabled = False
' Disable VarsTextBox
_VarsTextBox.DeselectAll()
_VarsTextBox.ClearUndo()
_VarsTextBox.Clear()
_VarsTextBox.Enabled = False
' Disable HackNameTextBox
_HackNameTextBox.DeselectAll()
_HackNameTextBox.ClearUndo()
_HackNameTextBox.Clear()
_HackNameTextBox.Enabled = False
' Disable RomCodeTextBox
_RomCodeTextBox.DeselectAll()
_RomCodeTextBox.ClearUndo()
_RomCodeTextBox.Clear()
_RomCodeTextBox.Enabled = False
' Disable NotesTextBox
_NotesTextBox.DeselectAll()
_NotesTextBox.ClearUndo()
_NotesTextBox.Clear()
_NotesTextBox.Enabled = False
Catch
Call _Misc.ErrorClose()
End Try
End Sub
Friend Sub _1()
Try
' Load flaglist
_FlagsTextBox.DeselectAll()
_FlagsTextBox.ClearUndo()
_FlagsTextBox.Clear()
_FlagsTextBox.Enabled = True
_FlagsTextBox.Text = My.Settings.Flaglist_1
' Load varlist
_VarsTextBox.DeselectAll()
_VarsTextBox.ClearUndo()
_VarsTextBox.Clear()
_VarsTextBox.Enabled = True
_VarsTextBox.Text = My.Settings.Varlist_1
' Load project name
_HackNameTextBox.DeselectAll()
_HackNameTextBox.ClearUndo()
_HackNameTextBox.Clear()
_HackNameTextBox.Enabled = True
_HackNameTextBox.Text = My.Settings.Hackname_1
' Load ROM codename
_RomCodeTextBox.DeselectAll()
_RomCodeTextBox.ClearUndo()
_RomCodeTextBox.Clear()
_RomCodeTextBox.Enabled = True
_RomCodeTextBox.Text = My.Settings.Romcode_1
' Load other notes
_NotesTextBox.DeselectAll()
_NotesTextBox.ClearUndo()
_NotesTextBox.Clear()
_NotesTextBox.Enabled = True
_NotesTextBox.Text = My.Settings.Notes_1
Catch
Call _Misc.ErrorClose()
End Try
End Sub
Friend Sub _2()
Try
' Load flaglist
_FlagsTextBox.DeselectAll()
_FlagsTextBox.ClearUndo()
_FlagsTextBox.Clear()
_FlagsTextBox.Enabled = True
_FlagsTextBox.Text = My.Settings.Flaglist_2
' Load varlist
_VarsTextBox.DeselectAll()
_VarsTextBox.ClearUndo()
_VarsTextBox.Clear()
_VarsTextBox.Enabled = True
_VarsTextBox.Text = My.Settings.Varlist_2
' Load project name
_HackNameTextBox.DeselectAll()
_HackNameTextBox.ClearUndo()
_HackNameTextBox.Clear()
_HackNameTextBox.Enabled = True
_HackNameTextBox.Text = My.Settings.Hackname_2
' Load ROM codename
_RomCodeTextBox.DeselectAll()
_RomCodeTextBox.ClearUndo()
_RomCodeTextBox.Clear()
_RomCodeTextBox.Enabled = True
_RomCodeTextBox.Text = My.Settings.Romcode_2
' Load other notes
_NotesTextBox.DeselectAll()
_NotesTextBox.ClearUndo()
_NotesTextBox.Clear()
_NotesTextBox.Enabled = True
_NotesTextBox.Text = My.Settings.Notes_2
Catch
Call _Misc.ErrorClose()
End Try
End Sub
Friend Sub _3()
Try
' Load flaglist
_FlagsTextBox.DeselectAll()
_FlagsTextBox.ClearUndo()
_FlagsTextBox.Clear()
_FlagsTextBox.Enabled = True
_FlagsTextBox.Text = My.Settings.Flaglist_3
' Load varlist
_VarsTextBox.DeselectAll()
_VarsTextBox.ClearUndo()
_VarsTextBox.Clear()
_VarsTextBox.Enabled = True
_VarsTextBox.Text = My.Settings.Varlist_3
' Load project name
_HackNameTextBox.DeselectAll()
_HackNameTextBox.ClearUndo()
_HackNameTextBox.Clear()
_HackNameTextBox.Enabled = True
_HackNameTextBox.Text = My.Settings.Hackname_3
' Load ROM codename
_RomCodeTextBox.DeselectAll()
_RomCodeTextBox.ClearUndo()
_RomCodeTextBox.Clear()
_RomCodeTextBox.Enabled = True
_RomCodeTextBox.Text = My.Settings.Romcode_3
' Load other notes
_NotesTextBox.DeselectAll()
_NotesTextBox.ClearUndo()
_NotesTextBox.Clear()
_NotesTextBox.Enabled = True
_NotesTextBox.Text = My.Settings.Notes_3
Catch
Call _Misc.ErrorClose()
End Try
End Sub
' Save all slots
Friend Sub SlotSaveAll()
Call _SaveSlot.FlaglistSave()
Call _SaveSlot.VarlistSave()
Call _SaveSlot.HacknameSave()
Call _SaveSlot.RomcodeSave()
Call _SaveSlot.NotesSave()
Call _SaveSlot.ExpandedSave()
End Sub
End Class
MainForm.vb
Public Class MainForm
' Class-level variables
Private _SlotSelect As New Flaglister.SlotSelect
Private _SaveSlot As New Flaglister.SaveSlot
Private _Misc As New Flaglister.Misc
' Startup/Shutdown events
Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Slot0RadioButton.Checked = True Then
Call _SlotSelect._0()
End If
End Sub
Sub MainForm_Deactivate(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Deactivate
My.Settings.Save()
Me.Close()
End Sub
' Form object events
Private Sub Slot0RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Slot0RadioButton.CheckedChanged
If Slot0RadioButton.Checked = True Then
Call _SlotSelect._0()
End If
End Sub
Private Sub Slot1RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Slot1RadioButton.CheckedChanged
If Slot1RadioButton.Checked = True Then
Call _SlotSelect._1()
End If
End Sub
Private Sub Slot2RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Slot2RadioButton.CheckedChanged
If Slot2RadioButton.Checked = True Then
Call _SlotSelect._2()
End If
End Sub
Private Sub Slot3RadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Slot3RadioButton.CheckedChanged
If Slot3RadioButton.Checked = True Then
Call _SlotSelect._3()
End If
End Sub
Private Sub FlagsTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlagsTextBox.TextChanged
Call _SaveSlot.FlaglistSave()
End Sub
Private Sub VarsTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VarsTextBox.TextChanged
Call _SaveSlot.VarlistSave()
End Sub
Private Sub HackNameTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HackNameTextBox.TextChanged
Call _SaveSlot.HacknameSave()
End Sub
Private Sub RomCodeTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RomCodeTextBox.TextChanged
Call _SaveSlot.RomcodeSave()
End Sub
Private Sub NotesTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NotesTextBox.TextChanged
Call _SaveSlot.NotesSave()
End Sub
Private Sub ExpandedCheckBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExpandedCheckBox.CheckedChanged
Call _SaveSlot.ExpandedSave()
End Sub
End Class
What's the problem in the code?
Here's some additional details about me and my program.
Computer
System: Seven x64 w/ AMD Sempron
Compiler: Microsoft Visual Basic 2010 Express
Application
Framework: Microsoft .NET version 3.5
Root Namespace: Flaglister
Assembly name: Flaglister
Application Type: Windows Forms Application
Sometimes I think too much, so I'm sorry if the answer is obvious to many and I don't see it.
EDIT
Here's a screenshot of the callstack at its current position when the error is thrown, and another screenshot of the popup error box. I would've never guessed to add these.
The issue here is recursive initialization. MainForm contains:
Private _SlotSelect As New Flaglister.SlotSelect
And SlotSelect contains:
Private _MainForm As Flaglister.MainForm = New Flaglister.MainForm
They keep calling each other's constructor, causing your stack overflow. You can fix this by passing in _MainForm as an argument in SlotSelect's constructor. Like so:
Public Class SlotSelect
' Class variables
Private _MainForm As Flaglister.MainForm
' (truncated for space)
Public Sub New(ByVal mainForm As Flaglister.MainForm)
Me._MainForm = mainForm
End Sub
'...
And in MainForm.vb, pass SlotSelect's constructor the current instance:
Private _SlotSelect As New Flaglister.SlotSelect(Me)
I'm guessing it is because in your class you are declaring and instantiating a new instance of MainForm
Private _MainForm As Flaglister.MainForm = New Flaglister.MainForm
Then in the MainForm class you are declaring and instantiating a new instance of the SlotSelect class
Private _SlotSelect As New Flaglister.SlotSelect
So the two classes just "bounce" back and forth creating new instances of each other, eventually giving you the stack overflow.
You are in an infinite loop.
In slotselect you have
Private _MainForm As Flaglister.MainForm = New Flaglister.MainForm
which creates a new main form, and then in MainForm you have
Private _SlotSelect As New Flaglister.SlotSelect
which creates a new slotselect.
Make one object the parent and one the child, and hand the parent reference in the constructor e.g.
Class SlotSelect
Private _MainForm As MainForm
Sub New(mf as MainForm)
_MainForm=mf
End Sub
...
End Class

Why do I get an InvalidOperationsException error?

Here's the deal. I tried using classes instead of the usual modules(in an attempt to try a different approach[aside from what I know that is] to OOP). So I used classes and in a simple showing and hiding of forms, I got an InvalidOperationsException error. Weirded out, I removed the OOP parts and just tried calling the other form directly on the form itself and still got the same error.
Here's the error I get:
An error occurred creating the form. See Exception.InnerException for details. The error is: The form referred to itself during construction from a default instance, which led to infinite recursion. Within the Form's constructor refer to the form using 'Me.'
Here's the code:
Private Sub btnNewSales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewOrder.Click
'This ought to have opened the new form via a method in the class
'order.NewOrder()
frmNewOrder.Show()
Me.Hide()
End Sub
either way, I get the same error.
Tried using modules instead. Here's the code:
Public Sub ShowForm(ByVal frmName As String)
If frmName = "Order" Then
frmOrders.Show()
ElseIf frmName = "AddOrder" Then
frmAddOrder.Show()
End If
End Sub
Now so far (in all my programming experience) this ought to work just fine, but it still returns the same error..
Update!
Tried removing all OOP aspects in form calling and left a module to simply show or hide some controls in one form.
Here's the code in the module:
Public Sub DesignSelect(ByVal design As String)
If design = "Basic" Then
frmAddOrder.lblD3.Hide()
frmAddOrder.cmbD3Color.Hide()
frmAddOrder.cmbD3Type.Hide()
frmAddOrder.lblD4.Hide()
frmAddOrder.cmbD4Color.Hide()
frmAddOrder.cmbD4Type.Hide()
Else
End If
End Sub
Now correct me if I'm wrong, but I do believe nothing is wrong with it right?
Now here's the code of the form where the module was used:
Dim selectedDesign As String = ""
Private Sub frmSalesTrans_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub frmSalesTrans_FormClosing(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
'ShowForm("Order")
frmOrders.Show()
End Sub
Private Sub rdbBasic_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbBasic.CheckedChanged
selectedDesign = "Basic"
DesignSelect(selectedDesign)
End Sub
And here's the code of the form that calls the form above:
Private Sub frmSales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnNewSales_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewOrder.Click
Me.Hide()
frmAddOrder.Show()
End Sub
Now it just boggles me why I get this error.. If I removed all OOP (including the subprocedure DesignSelect), it works fine. Kindly enlighten me on this...