Struggling student here... I've been asked to find the min, max and mid-point value. However, I cannot figure this out; arrays/data storage is 3 chapters away. So, I'm hoping someone could help me out with this conundrum.
-I need to get the data from an individual element within an array in decimal. Any ideas? I've largely been unsuccessful with the 'array.getvalue' method & with the 'array.min' methods.
Dim numberOfInvoices As Integer
Dim totalOfInvoices As Decimal
Dim invoiceAverage As Decimal
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim subtotal As Decimal = CDec(txtEnterSubtotal.Text)
Dim discountPercent As Decimal = 0.25D
Dim discountAmount As Decimal = Math.Round(subtotal * discountPercent, 2)
Dim invoiceTotal As Decimal = subtotal - discountAmount
Dim minimum, maximum, middle, i As Decimal
Dim array(1) As Decimal
Dim midpoint As Integer
txtSubtotal.Text = FormatCurrency(subtotal)
txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
txtDiscountAmount.Text = FormatCurrency(discountAmount)
txtTotal.Text = FormatCurrency(invoiceTotal)
numberOfInvoices += 1
totalOfInvoices += invoiceTotal
invoiceAverage = totalOfInvoices / numberOfInvoices
For i = 0 To numberOfInvoices - 1
array(i) = i
ReDim Preserve array(0 To numberOfInvoices - 1)
Next i
If numberOfInvoices = 1 Then
minimum = totalOfInvoices
middle = totalOfInvoices
maximum = totalOfInvoices
End If
If numberOfInvoices > 1 Then
midpoint = numberOfInvoices / 2
middle = array.GetValue(midpoint)
For Each i In array
If i < UBound(array) - 1 Then If array(i) > array(i + 1) Then maximum = array(i)
If i < UBound(array) - 1 Then If array(i) < array(i + 1) Then minimum = array(i)
Next i
End If
txtLargestInvoice.Text = maximum.ToString
txtSmallestInvoice.Text = minimum.ToString
txtMidPoint.Text = middle.ToString
txtNumberOfInvoices.Text = numberOfInvoices.ToString
txtTotalOfInvoices.Text = FormatCurrency(totalOfInvoices)
txtInvoiceAverage.Text = FormatCurrency(invoiceAverage)
txtEnterSubtotal.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnClearTotals_Click(sender As Object,
e As EventArgs) Handles btnClearTotals.Click
numberOfInvoices = 0
totalOfInvoices = 0
invoiceAverage = 0
txtNumberOfInvoices.Text = ""
txtTotalOfInvoices.Text = ""
txtInvoiceAverage.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnExit_Click(sender As Object,
e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Comments and explanations in-line
Private Sub OPCode2()
'You can declare and initialize an array in one line
Dim arr() As Double = {13.5, 18.0, 6.2, 11.8, 13.6}
'Just check intellisense for a list of methods and properties of arrays
Dim myAverage As Double = arr.Average()
Dim myMin As Double = arr.Min
Dim myMax As Double = arr.Max
Dim myMedian As Double
'The original array is lost when .Sort is applied
Array.Sort(arr)
Dim myLength As Integer = arr.Length
'If the lenght of the array is even you could also average
'the middle two values And return that number which
'may not be a value in the original array
myMedian = arr(CInt(myLength / 2)) 'returns the higher of the middle two if length is even
'or the actual middle value in the sorted array
MessageBox.Show($" The Average value is {myAverage}
The Maximum value is {myMax}
The Minimum value is {myMin}
The Median value is {myMedian}")
End Sub
Related
I'm developing a program that asks the user to input 5 numbers. The lowest of the 5 numbers will be dropped, and then the other 4 numbers are to be averaged.
I'm quite new to VB, but I believe I'm currently on the right path here...
I've sorted the array to help identify the lowest number, but I do not know how to exclude the lowest number and to then average the other remaining 4.
Here is my code so far:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim i As Integer
For i = 1 To 5
IntArr(4) = InputBox("Enter Number" & i)
Next
Array.Sort(IntArr)
'textbox1.text = ???
End Sub
End Class
Can anyone please assist or at least point me in the right direction?
In keeping with the spirit of your code, something like the following would work.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IntArr(4) As Integer
Dim OutArr(3) As Integer
For i = 0 To 4
IntArr(i) = InputBox("Enter Number " & i)
Next
Array.Sort(IntArr)
Array.Copy(IntArr, 1, OutArr, 0, 4) 'exclude the lowest number
TextBox1.Text = OutArr.Average()
End Sub
End Class
Using built in LINQ functions
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfItems = 5
Dim numberOfItemsToRemove = 1
Dim inArray(numberOfItems - 1) As Integer
Dim outArray(numberOfItems - 1 - numberOfItemsToRemove) As Integer
Dim i As Integer
For i = 0 To numberOfItems - 1
While Not Integer.TryParse(InputBox("Enter Number " & i + 1), inArray(i))
MessageBox.Show("Invalid input!")
End While
Next
outArray = inArray.OrderBy(Function(j) j).Skip(numberOfItemsToRemove).ToArray()
MessageBox.Show(
String.Format(
"Input: [{0}], Output: [{1}], average: {2:0.0}",
String.Join(", ", inArray),
String.Join(", ", outArray),
outArray.Average))
End Sub
Your code as it is above will continue to simply change the value of index 4 with each box if I'm not mistaken. I would do something like this (I will use your variable names for your convenience).
Button1_Click(procedure junk that is auto-inserted)
Dim intArr(4) As Integer
Dim OutArr(3) As Integer
Dim intCounter, intAverage, intLowest, intLowIndex As Integer
'populate all indexes of intArr()
For intCounter = 0 to 4
intArr(intCounter) = InputBox("Please enter a number.")
Next intCounter
intCounter = 1 'reset counter for check
intLowest = intArr(intLowIndex) 'start with index 0
'find lowest number and its index
For intCounter = 1 to 4
If intLowest > intArr(intCounter) Then 'defaults to previous
intLowest = intArr(intCounter)
intLowIndex = intCounter
End If
Next intCounter
intCounter = 0 'reset counter again for possible For...Next loops
Select Case intLowIndex
Case = 0
For intCounter = 0 to 3
OutArr(intCounter) = intArr(intCounter + 1)
Next intCounter
Case = 1
OutArr(0) = intArr(0)
OutArr(1) = intArr(2)
OutArr(2) = intArr(3)
OutArr(3) = intArr(4)
Case = 2
OutArr(0) = intArr(0)
OutArr(1) = intArr(1)
OutArr(2) = intArr(3)
OutArr(3) = intArr(4)
Case = 3
OutArr(0) = intArr(0)
OutArr(1) = intArr(1)
OutArr(2) = intArr(2)
OutArr(3) = intArr(4)
Case = 4
For intCounter = 0 to 3
OutArr(intCounter) = intArr(intCounter)
Next intCounter
End Select
intAverage = (OutArr(0) + OutArr(1) + OutArr(2) + OutArr(3)) / 4
'insert your preferred method to display OutArr() and intAverage
I need to make a phone bill program that would allow the user to calculate their phone bill. They would enter their minutes, texts and data allowance as well as how much they've used.
Each extra minute is 30p, each extra text is 10p and data used over the limit is £10.00, all added to the final cost.
The problem is that I cannot get the program to calculate the cost of each minute, I guess that after finding out how the minutes are calculated I will be able to do the same for the texts and the data.
Thanks for the help, much appreciated.
This is the problem
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btn1TotalCost_Click(sender As Object, e As EventArgs) Handles btn1TotalCost.Click
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim TextsAllowed As Integer
Dim TextsUsed As Integer
Dim DataAllowed As Integer
Dim DataUsed As Integer
Dim MinutesTotalCost As Double
Dim TextsTotalCost As Double
Dim DataTotalCost As Double
Dim MonthlyCost As Double
Dim TotalCost As Double
MinutesAllowed = Val(txtBoxMinutesAllowed.Text)
MinutesUsed = Val(txtBoxMinutesUsed.Text)
TextsAllowed = Val(txtBoxTextsAllowed.Text)
TextsUsed = Val(txtBoxTextsUsed.Text)
DataAllowed = Val(txtBoxDataAllowed.Text)
DataUsed = Val(txtBoxDataUsed.Text)
MinutesTotalCost = Val(txtBoxTotalCost.Text)
TextsTotalCost = Val(txtBoxTotalCost.Text)
DataTotalCost = Val(txtBoxTotalCost.Text)
TotalCost = Val(txtBoxTotalCost.Text)
'Minutes
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
'Texts
TextsAllowed = Integer.Parse(txtBoxTextsAllowed.Text)
TextsUsed = Integer.Parse(txtBoxTextsUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If TextsAllowed >= TextsUsed Then
TextsTotalCost = 0
Else
TextsTotalCost = (TextsUsed - TextsAllowed) * 0.15
End If
txtBoxTotalCost.Text = CType(TextsTotalCost + MonthlyCost, String)
'Data
DataAllowed = Integer.Parse(txtBoxDataAllowed.Text)
DataUsed = Integer.Parse(txtBoxDataUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If DataAllowed >= DataUsed Then
DataTotalCost = 0
Else
DataTotalCost = (DataUsed - DataAllowed) + 10.0
End If
txtBoxTotalCost.Text = CType(DataTotalCost + MonthlyCost, String)
End Sub
End Class
MinutesTotalCost = MinutesUsed - MinutesAllowed * 0.3
Multiplication and division operators have precedence over the addition and subtraction operators.
You need to add brackets to the calculation.
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
You also overwrite the result of the calculation here:
MinutesTotalCost = txtBoxTotalCost.Text
Edit: Working code for just the minutes
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim MinutesTotalCost As Double
Dim MonthlyCost As Double
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
Val() returns a double so you need to use Integer.Parse() for int.
Double needs to be converted to string for the textbox.
Edit 2:
Since MonthlyCostdoesn't change you need the line
MonthlyCost = Val(txtBoxMonthlyCost.Text)
only once at the beginning.
You are always overwriting the value of txtBoxTotalCost. Just make a single calculation with all costs i.e.
txtBoxTotalCost.Text = CType(MinutesTotalCost + TextsTotalCost + DataTotalCost + MonthlyCost, String)
I started a new project which loads and saves tilesets in style of ini-datas.
The problem is now, that it loads the tiles into a 1d- list, which got copied sorted into a 1d-array.
Now I am trying to convert this sorted 1d-array into a 2d-array.
My try:
LoadedTiles.Sort(Function(p1, p2) (p1.Position.X.CompareTo(p2.Position.X)))
LoadedTiles.Sort(Function(p1, p2) (p1.Position.Y.CompareTo(p2.Position.Y)))
Dim currentArray(AmountTiles) As Tile
currentArray = LoadedTiles.ToArray
Dim lengthX, lengthY As Integer
Dim yAxis As Integer = currentArray(0).Position.Y
For Each p In currentArray
If Not p.Position.Y = yAxis Then
lengthX = (p.Position.X / p.Size.Width)
lengthY = (currentArray(currentArray.Length - 1).Position.Y / p.Size.Width)
Else
lengthX = (currentArray(currentArray.Length - 1).Position.X / p.Size.Width)
lengthY = 0
End If
Next
MapTiles = New Tile(lengthX, lengthY) {}
Dim ii As Integer
For x = 0 To lengthX
For y = 0 To lengthY
MapTiles(x, y) = currentArray(ii)
If Not ii >= currentArray.Length - 1 Then
ii += 1
End If
Next
Next
This gives a wrong output.
See picture below:
http://www.directupload.net/file/d/3690/pz8x98jr_png.htm
Is it possible to do it right?
Thanks alot!
The k-th element in a 1D array can correspond to row i=k/N and column j=k%N where N is the number of columns. The reverse is k=i*N+j
Ok guys, I got it ( =
Public Class Form1
Dim List As New List(Of Point)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
List.Add(New Point(180, 360))
List.Add(New Point(180, 180))
List.Add(New Point(180, 540))
'Convert 1d to 2d
Dim count As Point = countXYAxis(List, 180)
MsgBox(count.ToString)
Dim p(count.X - 1, List.Count - 1) As Point
MsgBox(p.Length)
Dim rofl As Integer
For i = 0 To p.GetUpperBound(0)
For j = 0 To p.GetUpperBound(1)
p(i, j) = List(rofl)
If Not rofl >= List.Count - 1 Then
rofl += 1
End If
Next
Next
For Each t In p
MsgBox(t.ToString)
Next
End Sub
Private Function countXYAxis(ByVal pt As List(Of Point), ByVal size As Integer) As Point
Dim bufferY As New List(Of Integer)
Dim cP As New Point
For Each pts In pt
If Not bufferY.Contains(pts.Y) Then
bufferY.Add(pts.Y)
End If
Next
For i = 0 To pt.Count - 1
If pt(i).Y = bufferY(0) Then
Else
cP = New Point(pt(i).X / size, bufferY.Count)
End If
Next
Return cP
End Function
End Class
I am computing the ROI with a moving rectangle and extracting the ROI to compute the standard deviation, mean, area and Pixel value coordinates X and Y in a seperate form2 by clicking the mouse. At this juncture I am trying to pass a function from the main Form that loads the Image and displays the rectangle to another Form that has the displayed properties of the mean and standard deviation etc. However, I'm receiving errors in runtime in the function that contains the standard deviation. The error displayed is
Index was outside the bounds of the array.
It is displayed at the end of this portion of the code in the function StD, i.e at the end of the mean part'
SD(count) = Double.Parse(pixelcolor.R) + Double.Parse(pixelcolor.G) + Double.Parse(pixelcolor.B) - mean
what is this actually saying and how can I fix this situation. Any tips and ideas, thanks.
My code is at the bottom
enterPublic Function StD(ByVal image As Bitmap, ByVal mean As Double, ByVal meancount As Integer) As Double
Dim SD(SquareHeight * SquareWidth) As Double
Dim count As Integer = 0
For i = 0 To SquareWidth
For j = 0 To SquareHeight
Dim pixelcolor As Color = image.GetPixel(i, j)
SD(count) = Double.Parse(pixelcolor.R) + Double.Parse(pixelcolor.G) + Double.Parse(pixelcolor.B) - mean
count += 1
Next
Next
Dim SDsum As Double = 0
For i = 0 To count
SDsum = SDsum + SD(i)
Next
SDsum = SDsum / (SquareHeight * SquareWidth)
SDsum = ((SDsum) ^ (1 / 2))
Return SDsum
End Function code here
I would like to pass this using the code below
enterPrivate Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
Dim mean As Double = 0
Dim meancount As Integer = 0
Dim bmap As New Bitmap(400, 400)
bmap = PictureBox1.Image
Dim colorpixel As Color = bmap.GetPixel(e.X, e.Y)
' Dim pixels As Double = colorpixel.R + colorpixel.G + colorpixel.B
If e.Button = Windows.Forms.MouseButtons.Left AndAlso Rect.Contains(e.Location) Then
If (PictureBox1.Image Is Nothing) Or (PictureBox1.Height - (e.Y + SquareHeight) < 0) Or (PictureBox1.Width - (e.X + SquareWidth) < 0) Then
Else
Dim ROI As New Bitmap(400, 400)
Dim x As Integer = 0
Dim countx As Integer = 0
Dim county As Integer = 0
For i = e.X To (e.X + SquareWidth)
For j = (e.Y + x) To (e.Y + SquareHeight)
Dim pixelcolor As Color = bmap.GetPixel(i, j)
ROI.SetPixel(countx, county, pixelcolor)
mean = mean + pixelcolor.R + pixelcolor.G + pixelcolor.B
county += 1
meancount += 1
Next
county = 0
countx += 1
x = x + 1
Next
mean = mean / (meancount * 3)
Dim SD = mean - 75
Dim area As Integer = (SquareHeight * SquareWidth)
Dim anotherForm As Form2
anotherForm = New Form2(mean, StD(bmap, mean, meancount), area, 34)
anotherForm.Show()
End If
End If
' Catch ex As Exception
' MessageBox.Show(ex.Message())
' End Try
End Sub code here
To be displayed with this code
enter Public Sub New(ByVal mean As Double, ByVal StD As Double, ByVal Area As Integer, ByVal pixel As Double)
MyBase.New()
InitializeComponent()
TextBox1.Text = mean.ToString()
TextBox2.Text = StD.ToString()
TextBox3.Text = Area.ToString()
TextBox4.Text = pixel.ToString()
End Sub code here
The problem probably is because of these lines:
For i = 0 To SquareWidth
For j = 0 To SquareHeight
Try using this instead:
For i = 0 To SquareWidth - 1
For j = 0 To SquareHeight - 1
Thanks for reading - I am using the class below to calculate the CRC32 checksum of a specified file.
My question is how would I go about reporting the progress of file completion (in %) to a progressbar on a different form. I have tried (i / count) * 100 under the New() sub but I am not having any luck, or setting the progress bar with it for that matter. Can anyone help?
Thanks in advance
Steve
Public Class CRC32
Private crc32Table() As Integer
Private Const BUFFER_SIZE As Integer = 1024
Public Function GetCrc32(ByRef stream As System.IO.Stream) As Integer
Dim crc32Result As Integer
crc32Result = &HFFFFFFFF
Dim buffer(BUFFER_SIZE) As Byte
Dim readSize As Integer = BUFFER_SIZE
Dim count As Integer = stream.Read(buffer, 0, readSize)
Dim i As Integer
Dim iLookup As Integer
Do While (count > 0)
For i = 0 To count - 1
iLookup = (crc32Result And &HFF) Xor buffer(i)
crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
crc32Result = crc32Result Xor crc32Table(iLookup)
Next i
count = stream.Read(buffer, 0, readSize)
Loop
GetCrc32 = Not (crc32Result)
End Function
Public Sub New()
Dim dwPolynomial As Integer = &HEDB88320
Dim i As Integer, j As Integer
ReDim crc32Table(256)
Dim dwCrc As Integer
For i = 0 To 255
Form1.CRCWorker.ReportProgress((i / 255) * 100) 'Report Progress
dwCrc = i
For j = 8 To 1 Step -1
If (dwCrc And 1) Then
dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
dwCrc = dwCrc Xor dwPolynomial
Else
dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
End If
Next j
crc32Table(i) = dwCrc
Next i
'file complete
End Sub
End Class
'------------- END CRC32 CLASS--------------
'-------------- START FORM1 --------------------------
Private Sub CRCWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles CRCWorker.DoWork
For i = CurrentInt To dgv.Rows.Count - 1
CRCWorker.ReportProgress(0, i & "/" & Total_Files)
Current_File_Num = (i + 1)
SetControlText(lblCurrentFile, Str(Current_File_Num) & "/" & Total_Files)
result = CheckFile(SFV_Parent_Directory & "\" & dgv.Rows(i).Cells(0).Value, dgv.Rows(i).Cells(1).Value)
Select Case result
Case 0 ' missing file
UpdateRow(i, 2, "MISSING")
'dgv.Rows(i).Cells(2).Value = "MISSING"
Missing_Files = Missing_Files + 1
SetControlText(lblMissingFiles, Str(Missing_Files))
Case 1 ' crc match
UpdateRow(i, 2, "OK")
' dgv.Rows(i).Cells(2).Value = "OK"
Good_Files = Good_Files + 1
SetControlText(lblGoodFiles, Str(Good_Files))
Case 2 'crc bad
UpdateRow(i, 2, "BAD")
' dgv.Rows(i).Cells(2).Value = "BAD"
Bad_Files = Bad_Files + 1
SetControlText(lblBadFiles, Str(Bad_Files))
End Select
If CRCWorker.CancellationPending = True Then
e.Cancel = True
Exit Sub
End If
Next
End Sub
Private Sub CRCWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles CRCWorker.ProgressChanged
Dim val As Integer = e.ProgressPercentage
ProgressBar2.Maximum = 100
ProgressBar2.Value = e.ProgressPercentage
Debug.Print(val)
End Sub
Function CheckFile(ByVal tocheck_filepath As String, ByVal expected_crc As String) As Integer 'returns result of a file check 0 = missing 1 = good 2 = bad
If File.Exists(tocheck_filepath) = False Then
Return 0 'return file missing
End If
Dim f As FileStream = New FileStream(tocheck_filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
Dim c As New CRC32()
crc = c.GetCrc32(f)
Dim crcResult As String = "00000000"
crcResult = String.Format("{0:X8}", crc)
f.Close()
End Function
It appears your .ReportProgress() call is in the New() subroutine, which is the part that makes the lookup table for the CRC calculation. The New() subroutine is called once, before the main CRC routine. The main CRC routine is the one that takes up all the time and needs the progress bar.
Shouldn't the progress bar updating be in the GetCrc32() function? Something like this:
Public Function GetCrc32(ByRef stream As System.IO.Stream, _
Optional prbr As ProgressBar = Nothing) As UInteger
Dim crc As UInteger = Not CUInt(0)
Dim buffer(BUFFER_SIZE) As Byte
Dim readSize As Integer = BUFFER_SIZE
Dim left As Long = stream.Length
If Not (prbr Is Nothing) Then ' ProgressBar setup for counting down amount left.
prbr.Maximum = 100
prbr.Minimum = 0
prbr.Value = 100
End If
Dim count As Integer : Do
count = stream.Read(buffer, 0, readSize)
For i As Integer = 0 To count - 1
crc = (crc >> 8) Xor tbl((crc And 255) Xor buffer(i))
Next
If Not (prbr Is Nothing) Then ' ProgressBar updated here
left -= count
prbr.Value = CInt(left * 100 \ stream.Length)
prbr.Refresh()
End If
Loop While count > 0
Return Not crc
End Function
In Windows Forms BackgroundWorker Class is often used to run intensive tasks in another thread and update progress bar without blocking the interface.
Example of using BackgroundWorker in VB.Net
The problem is when you use use the form in your code without instantiating it Form1.CRCWorker.ReportProgress((i / 255) * 100) there is a kind of hidden "auto-instantiation" happening and new instance of Form1 is created each time.