Getting an object reference error in VB.net - 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

Related

Why is this CInt function call *not* throwing an error?

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.

{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.

vb.net textbox not displaing value

In my frmMain class I have a textbox(txtCustomer) which populates from a database. I want to pass this value to another textbox in frmDepartment(txtDeptCustomer).
I am failing to see the logic of why the code I am using is not displaying a value in txtDeptCustomer. I can query the database ok with the variable, so the string is being passed through, but just not displaying in txtDeptCustomer. I would be grateful if someone could point out my error. Thanks
frmDepartment
Dim customer As Object = frmMain.txtCustomer.Text
This is passing correct value to db.
sql = "SELECT * FROM Departments where Customer = '" & CType(customer, String) & "'"
textbox txtDeptCustomer <--- NOT DISPLAYING VALUE
Private Sub txtDeptCustomer_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDeptCustomer.TextChanged
txtDeptCustomer.Text = CType(customer, String)
End Sub
Public Customer as String = Nothing
Private Sub btnDO_Click(sender As Object, e As EventArgs) Handles btnDoWork.Click
Customer = Database Call
Dim frmDepartmentInstance as new frmDepartment
frmDepartment.ShowDialog(Me)
End Sub
Then in the Load event of frmDepartment you can say
txtDeptCustomer.Text = frmMain.Customer
Proof of concept: New Project. Two forms | Form 1 has a button and a textbox | Form2 just has textbox
Public Class Form1
Public Test As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Test = TextBox1.Text
Dim frm2 As New Form2
frm2.ShowDialog(Me)
End Sub
End Class
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = Form1.Test
End Sub
End Class
You must declare then as public your customer variable in frmDepartment, like:
Public customer as String
And in the button click from your frmMain you pass the value like:
frmDepartment.customer = txtCustomer.Text
frmDepartment.Show()
And then in Loading your frmDepartment you have now the option of assigning customer to txtDeptCustomer like:
Private Sub frmDepartment_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
txtDepartment.Text = customer
End Sub

Custom control mybase.OnTextChanged not firing

I have a custom text box control which validates input (striped out unwanted chars). This works fine apart from when I also want to do further processing on an implementation of the control.
Example I have 3 "specialTextbox"s on a form. sText1, sText2 and sText3. sText1 & sText2 work as as intended. However, I need to make changes on the forum when the value of sText3 is changed, so I have a handler in the form to handle the ctext changed event:
Private Sub sText3(sender As Object, e As EventArgs) Handles sText3.TextChanged
'do some stuff here
End Sub
However this routine appears to override the OnTextChanged method of the custom text box. I have tried includeing a call to MyBase.OnTextChanged, but this still doesn't cascade up and no matter what I do I can't seem to get the text box to do its validation duties.
Must be something really simple, but I'm stumped!
Here is a class which overrides textbox
Public Class restrictedTextBox
Inherits Windows.Forms.TextBox
Protected validChars As List(Of Char)
Public Sub New(ByVal _validChars As List(Of Char))
MyBase.New()
validChars = _validChars
End Sub
Public Sub setValidChars(ByVal chrz As List(Of Char))
validChars = chrz
End Sub
Protected Overrides Sub OnTextChanged(e As System.EventArgs)
MyBase.OnTextChanged(e)
Dim newValue As String = ""
For Each c As Char In Me.Text.ToCharArray
Dim valid As Boolean = False
For Each c2 As Char In validChars
If c = c2 Then valid = True
Next
If valid Then newValue &= c.ToString
Next
Me.Text = newValue
End Sub
End Class
Here is a form which has a a custom textbox
Public Class frmNewForm
Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
MessageBox.Show("the text from the restricted text is: " & txtRestricted.Text)
End Sub
End Class
Here is a form with a custom text box, which implements the TextChanged event
Public Class frmNewForm2
Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
MessageBox.Show("the text from the restricted text is: " & txtRestricted.Text)
End If
Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs) Handles txtRestricted.TextChanged
'now that I have implemented this method, the restrictedTextBox.OnTextChanged() doesn't fire - even if I call MyBase.OnTextChanged(e)
'just to be completely clear. the line of code below DOES get executed. But the code in restrictedTextBox.vb does NOT
lblAwesomeLabel.Text=txtRestricted.Text
End Sub
End Class
It fires, but probably not the way you are implementing it.
Your sample code does not have an empty constructor for the textbox, which means you are most likely not using the designer when you are adding the textbox to the form.
But your form shows it was created by the designer:
Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs) _
Handles txtRestricted.TextChanged
End Sub
That's not possible with your posted code. If you are creating "new" controls programmatically, then you need to wire up the events programmatically, too.
Drop the handler and just leave the stub:
Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs)
'yada-yada-yada
End Sub
then when you create a new textbox, wire it up:
txtRestricted = new restrictedTextBox(myCharsList)
AddHandler txtRestricted.TextChanged, AddressOf txtRestricted_TextChanged
Me.Controls.Add(txtRestricted)

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