Object reference not set to instance of an object in VB.NET - vb.net

Why am I getting the error "Object reference not set to instance of an object" with my code?
Public Class Form2
Dim i As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click
Me.Close()
End Sub
Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPatient.Click
Names(i) = txtPatientName.Text
i = i + 1
End Sub
End Class
Names() is a global variable
Thanks
Updated:
Module Module1
Public Names() As String
Public Heights() As Integer
Public Weights() As Integer
End Module
Public Class Form2
Dim i As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click
Me.Close()
End Sub
Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPatient.Click
ReDim Preserve Names(0 To i)
Names(i) = txtPatientName.Text
ReDim Preserve Heights(0 To i)
Heights(i) = txtPatientHeight.Text
ReDim Preserve Weights(0 To i)
Weights(i) = txtPatientWeight.Text
i = i + 1
End Sub
End Class

If you insist on using a module, you should redim preserve your array.
Public Module Module1
Public i As Integer = 0
Public Names() As String
Public Heights() As Integer
Public Weights() As Integer
End Module
Public Class Form1
Dim i As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ReDim Preserve Names(0 To i)
Names(i) = txtpatientName.Text
ReDim Preserve Heights(0 To i)
Heights(i) = txtpatientheight.Text
ReDim Preserve Weights(0 To i)
Weights(i) = txtpatientweight.Text
i = i + 1
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For Each j In Names
MsgBox(j.ToString)
Next
End Sub
End Class

You need to make module as public. So i suggest below
Public Module Module1
Public Names() As String
Public Heights() As Integer
Public Weights() As Integer
End Module
Then access it in form like
Dim mod1 = Module1
mod1.Names(i) = txtPatientName.Text

Related

Error : reference to a non-shared member requires an object reference

The game i am making is connect 4 , the form I am calling from is here :
Public Class Form1
Public players(1) As IPlayer
Public playerturn As IPlayer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
buttons()
init()
End Sub
Public Sub init()
playerturn = players(0)
Board1.Init()
currentaturn.Text = String.Format("{0}'s turn", playerturn.name)
End Sub
Sub buttons()
For i As Integer = 0 To 7
Dim btn As New Button()
btn.Text = "drop"
btn.BackColor = Color.Pink
btn.Size = New Size(40, 40)
btn.Location = New Point(i * 48, 0)
btn.Tag = i
AddHandler btn.Click, AddressOf clickbutton
Panel1.Controls.Add(btn)
Next
End Sub
Sub clickbutton(ByVal sender As Object, ByVal e As EventArgs)
Dim clickedbutton As Button = CType(sender, Button)
Dim clickedcolumn As Integer = clickedbutton.Tag
If (Board1.addpiecetocolumn(clickedcolumn, Color.Red) = False) Then
Else
End If
End Sub
Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LDBTN.Click
End Sub
Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles currentaturn.Click
End Sub
Private Sub RESETBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RESETBTN.Click
loginsys.Show()
Me.close
End Sub
End Class
and the form I am calling to :
Public Class board
Public board(8, 8) As panelbox
Public columns As Integer = 7
Public rows As Integer = 7
Public Sub New()
InitializeComponent()
Init()
End Sub
Public Sub Init()
Me.Controls.Clear()
For i As Integer = 0 To columns - 1
For j As Integer = 0 To rows - 1
board(i, j) = New panelbox()
board(i, j).Size = New Size(50, 50)
board(i, j).Location = New Point((i * 45), (j * 45))
board(i, j).BackColor = Color.DodgerBlue
Me.Controls.Add(board(i, j))
Next
Next
End Sub
Public Function addpiecetocolumn(ByVal x As Integer, ByVal colo As Color) As Boolean
For y As Integer = rows - 1 To 0 Step -1
If (board(x, y).Used = False) Then
board(x, y).Used = True
board(x, y).BackColor = colo
Return True
End If
Next
Return False
End Function
End Class
it should be noted that I am naming the second form board and the part that's calling the error is from the first form :
Public Sub init()
playerturn = players(0)
Board1.Init()
currentaturn.Text = String.Format("{0}'s turn", playerturn.name)
End Sub
Any help would be great
Use Public Shared Function function_name, in this case, you have to call it like board.function_name

Error: Form1 is a type of windowsApplication cannot be used as an expression

How to solve error when passing and returning some data across the form in visual basic.
Error: Form1 is a type of windowsApplication cannot be used as an
expression
showin error on "Form 1" (Public Class Form1)
FORM 1 CODE
Public Class Form1
Dim eid As String = ""
Public Sub New(ByVal empid As String)
InitializeComponent()
eid = empid
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Declare a variable of string type
Dim pass As String = TextBox1.Text
Dim frm As New Form2(pass)
frm.ShowDialog()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label2.Text = eid.ToString()
End Sub
End Class
FORM 2 CODE
Public Class Form2
Dim eid As String = ""
Public Sub New(ByVal empid As String)
InitializeComponent()
eid = empid
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = eid.ToString()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim value As String = TextBox2.Text
Dim fr As New Form1(value)
fr.ShowDialog()
End Sub
End Class
To solve your error message add this to your Form1 Class
Public Sub New()
InitializeComponent()
End Sub
If you are trying to pass values between forms, you might find this link useful...
http://grantwinney.com/passing-data-between-two-forms-in-winforms/
Public Class Form1
Dim eid As String = ""
Public Sub New(ByVal empid As String)
InitializeComponent()
eid = empid
End Sub
Public Sub New()
InitializeComponent()
End Sub
startup form isn't being called with any parameters
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Declare a variable of string type
Dim pass As String = TextBox1.Text
Dim frm As New Form2(pass)
frm.ShowDialog()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label2.Text = eid.ToString()
End Sub
End Class
It happens when you change the project type from class library to windows forms in visual studio.
Head to Application.Designer.vb in your project and there you'll find something like this:
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AeonLabs.Layouts.Main.mainAppLayoutForm
End Sub
End Class
End Namespace
in the sub OnCreateMainForm() where it has OnCreateMainForm change it to something like this
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = New Global.AeonLabs.Layouts.Main.mainAppLayoutForm
End Sub
and you'll be good to go!!

Public variables, when outputted are outputted as a "0" when a string is entered

im making a program for school (in VB.NET) where i have a listview. When the user enters a customer name and presses "OK"it is outputted in the listview as a "o"
the code for the program is:
Public Class Form1
Dim w As IO.StreamWriter
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
lstOutput.Items.Clear()
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
End
End Sub
Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem.Click
Dim sfile As New SaveFileDialog
With sfile
.Title = "Choose your path to save the information"
.InitialDirectory = "C:\"
.Filter = ("ONLY Text Files (*.txt) | *.txt")
End With
If sfile.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim Write As New IO.StreamWriter(sfile.FileName)
Dim k As ListView.ColumnHeaderCollection = lstOutput.Columns
For Each x As ListViewItem In lstOutput.Items
Dim StrLn As String = ""
For i = 0 To x.SubItems.Count - 1
StrLn += k(i).Text + " :" + x.SubItems(i).Text + Space(3)
Next
Write.WriteLine(StrLn)
Next
Write.Close() 'Or Write.Flush()
End If
End Sub
Private Sub txtDiscPrice_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub btnAdd_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim secondform As New Form2
secondform.ShowDialog()
Dim item As ListViewItem
item = lstOutput.Items.Add(secondform.CustomerName)
item.SubItems.Add(secondform.Item)
item.SubItems.Add(secondform.ItemPrice)
item.SubItems.Add(secondform.Quantity)
item.SubItems.Add(secondform.TotalPrice)
item.SubItems.Add(secondform.DiscPerc)
item.SubItems.Add(secondform.DiscPrice)
item.SubItems.Add(secondform.PaymentMethod)
End Sub
End Class
and for the second form, where the user enters the information the code is:
Public Class Form2
Public CustomerName As String
Public Item As String
Public ItemPrice As Double
Public Quantity As Integer
Public TotalPrice As Integer
Public DiscPerc As Double
Public DiscPrice As Double
Public PaymentMethod As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CustomerName = Val(txtCustName.Text)
Item = Val(txtItemName.Text)
ItemPrice = Val(txtItemPrice.Text)
Quantity = Val(txtQuantity.Text)
TotalPrice = Val(txtTtlPrice.Text)
DiscPerc = Val(txtDiscPerc.Text)
DiscPrice = Val(txtDiscPrice.Text)
PaymentMethod = Val(txtPaymentMethod.Text)
Me.Close()
End Sub
End Class
I've been stuck on this for ages, any help is appreciated!

'While Loop' and multiples of a variable

This is another school project, and I'm stumped, so PLEASE help.
I'm supposed to write a program that outputs the numbers 1 to 100, however there are 4 variables. When you enter a value for Variable 1 it takes the numbers that multiples of that number and changes it to the Variable Word that you type in.
The specific question I have is how do I get my variables to be multiples of that value?
This is all I have...thank you for your help.
Public Class Form1
Private Sub lblDiscription_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblDiscription.Click
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub bntCounter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntCounter.Click
Dim intCounter As Integer = 0
Dim intLeftMultiple As Integer = 1
Dim intRightMultiple As Integer = 1
Dim strLeftWord As String
Dim strRightWord As String
While intCounter < 101
lstDisplay.Items.Add(CStr(intCounter))
intCounter += 1
End If
End While
End Sub
Private Sub lblMiddle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblMiddle.Click
End Sub
End Class
This is what my GUI Looks like.

String Manipulation by hiding and showing

The idea is simple, if I have a string value "ABCD" then with a ButtonClick event it should randomly reveal a char while others are hidden. i.e, "B*" another click would "AB**" and so on.
So far, my I have been stuck in a for loop.
For Each c As Char In x
y = Random.Next(0, x.IndexOf(c))
Next
I'm still learning VB.NET at this phase.
Public Class Form1
Private _indexes As Integer()
Private _currentIndex As Integer
Private _chars As Char()
Private _template As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rnd = New Random()
_template = "ABCD"
' Create indexes that are randomly sorted
_indexes = Enumerable _
.Range(0, _template.Length) _
.OrderBy(Function(i) rnd.Next()) _
.ToArray()
'Create an array of chars with stars '****'.
_chars = New String("*"c, _template.Length).ToCharArray()
_currentIndex = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If _currentIndex < _template.Length Then
Dim index As Integer = _indexes(_currentIndex)
_currentIndex += 1
_chars(index) = _template(index)
Dim result As String = New String(_chars)
Label1.Text = result
End If
End Sub
End Class
I have already posted an answer where I focused on the algorithm. The algorithm code was directly integrated into a form. This works but is not a good practice. The code would be more reusable, more understandable and could be tested more easily if it was extracted to a separate class.
Public Class RandomTextRevealer
Private _indexes As Integer()
Private _currentIndex As Integer
Private _chars As Char()
Private _template As String
Private _result As String
Public Sub New(ByVal templateText As String)
Dim rnd = New Random()
_template = templateText
' Create indexes that are randomly sorted
_indexes = Enumerable _
.Range(0, _template.Length) _
.OrderBy(Function(i) rnd.Next()) _
.ToArray()
'Create an array of chars with stars '****'.
_chars = HiddenText.ToCharArray()
_currentIndex = 0
End Sub
Public Function RevealNext() As String
If _currentIndex < _template.Length Then
Dim index As Integer = _indexes(_currentIndex)
_currentIndex += 1
_chars(index) = _template(index)
_result = New String(_chars)
End If
Return _result
End Function
Public ReadOnly Property HiddenText() As String
Get
Return New String("*"c, _template.Length)
End Get
End Property
End Class
We can test the class like this in a little console application, without a form:
Module Programm
Public Sub Main()
Dim revealer = New RandomTextRevealer("Just a test")
Console.WriteLine(revealer.HiddenText)
For i As Integer = 1 To 12
Console.WriteLine(revealer.RevealNext())
Next
Console.ReadKey()
End Sub
End Module
Now we can integrate it in a form like this (I added a Reset-button, in order to be able to repeat the test with different random values):
Public Class Form2
Dim revealer As RandomTextRevealer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Reset()
End Sub
Private Sub btnReveal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReveal.Click
Label1.Text = revealer.RevealNext()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
Reset()
End Sub
Private Sub Reset()
revealer = New RandomTextRevealer("ABCD")
Label1.Text = revealer.HiddenText
End Sub
End Class
Now our form-code looks much cleaner.