When running the code the program will run to complete one cycle, then the arduino must be disconnected and reconnected (unplugged and replugged in) in order to run again. Sometimes the program will even stop halfway through.
I am very new to VB programming and any help would be appreciated
There is no problem with the arduino code, it was fully tested before creating the VB user form.
tried running on multiple computers/Operating systems same results
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
''reads data from arduino
Dim datastream As String
datastream = (SerialPort1.ReadLine)
'' RichTextBox1.Text = datastream
Data_manipulate(arr:=datastream)
End Sub
Public Sub Data_manipulate(ByRef arr As String)
''processes data to calculate linearity
Dim linearity As Single
Dim percent As Single
Dim nominal As Single
ReDim Preserve points(i)
ReDim Preserve counts(i)
Dim values As String() = arr.Split(New Char() {","c})
percent = values(0) / values(3)
nominal = values(1) / values(2)
linearity = (percent - nominal) * 100
TextBox3.Text = values(2) * (0.00118)
points(i) = linearity
counts(i) = nominal * 100
TextBox8.Text = (points).max
TextBox10.Text = points.Min
Chart1.Series("Linearity").Points.AddXY(counts(i), points(i))
''Chart1.Series("Linearity").Points.AddXY(counts(i), points(i))
If points.Max > NumericUpDown1.Value Then
TextBox8.BackColor = Color.Red
End If
If points.Min < -NumericUpDown1.Value Then
TextBox10.BackColor = Color.Red
End If
If nominal < 0.5 Then
TextBox13.Text = values(1) * (0.00118)
Dim Halfpercent As Double = values(1) * 0.00118
If ((0.5 * (values(2) * 0.00118)) - 0.015) < Halfpercent AndAlso Halfpercent < ((0.5 * (values(2) * 0.00118)) + 0.015) Then
TextBox13.BackColor = Color.LimeGreen
Else TextBox13.BackColor = Color.Red
End If
End If
If percent = 1 Then
Auto_Slope_And_Level_Button_Click()
End If
i += 1
End Sub
Private Sub Connect_Button_click(sender As Object, e As EventArgs) Handles Connect_Button.Click
If ComboBox1.SelectedItem Is Nothing Then
MessageBox.Show("Please Select a Port")
Return
End If
SerialPort1.BaudRate = 9600
SerialPort1.PortName = ComboBox1.SelectedItem
If Connect_Button.Text = "Connect" Then
Try
SerialPort1.Open()
Connect_Button.Text = "Connected"
Disconnect_Button.Text = "Disconnect"
Connect_Button.BackColor = Color.LimeGreen
Catch ex As Exception
End Try
Else
End If
End Sub
Private Sub Start_Button_Click(sender As Object, e As EventArgs) Handles Start_Button.Click
If SerialPort1.IsOpen Then
Chart1.Series("Linearity").Points.Clear()
ReDim points(0)
ReDim counts(0)
SerialPort1.Write(1)
TextBox8.Text = 0
TextBox10.Text = 0
TextBox2.Text = 0
Else
MessageBox.Show("Not Connected")
Return
End If
End Sub
Private Sub Disconnect_Button_Click(sender As Object, e As EventArgs) Handles Disconnect_Button.Click
Try
SerialPort1.Close()
Disconnect_Button.Text = "Disconnected"
Connect_Button.Text = "Connect"
Connect_Button.BackColor = Color.FromArgb(255, 0, 0)
Catch ex As Exception
End Try
End Sub
Private Sub ComboBox1_DropDown(sender As Object, e As EventArgs) Handles ComboBox1.DropDown
ComboBox1.Items.Clear()
Try
For Each port As String In SerialPort.GetPortNames
ComboBox1.Items.Add(port)
Next
ComboBox1.SelectedItem = ""
Catch ex As Exception
End Try
End Sub
A "com port does not exist" error will occur if you don't reset between runs.
If the program stops partway through the computer needs either a log-off or restart to reconnect with the arduino.
Related
I am new to vb and I'm trying to split serial data received from the Arduino board on Visual Basic. I've watched and followed tutorials online that outputs all the serial data in one textbox and it works. But now i need to split the data into textboxes that correspond to the sensor (i have 5 sensors).
I've tried using .Split and arrays to split and then store the data before moving it to the corresponding textbox but it doesn't work.
Appreciate all the help I can get
Dim receivedData As String = ""
Private Sub AirQuality_Load(sender As Object, e As EventArgs) Handles Me.Load
GetSerialPortNames()
Timer1.Enabled = False
txtPmax.Text = 14.7
txtPmin.Text = 10
txtO2max.Text = 21
txtO2min.Text = 15
txtCO2.Text = 1000
txtP25.Text = 25
txtP10.Text = 50
txtCO.Text = 35
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
cbCOMPort.Items.Add(sp)
Next
cbCOMPort.SelectedIndex = 0
End Sub
Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
Try
If (btnConnect.Text = "Connect") Then
If (cbCOMPort.Text <> "") Then
'Open Serial Port
SerialPort1.Close()
SerialPort1.PortName = cbCOMPort.Text
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default 'very important!
SerialPort1.ReadTimeout = 10000
SerialPort1.Open()
btnConnect.Text = "Dis-connect"
Timer1.Enabled = True
btnUpdate.PerformClick()
Else
MsgBox("Select a COM port first")
End If
Else
SerialPort1.Close()
btnConnect.Text = "Connect"
Timer1.Enabled = False
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Function ReceiveSerialData() As String
Dim Incoming As String
Dim Array() As String
Incoming = SerialPort1.ReadExisting
Array = Split(Incoming, ";")
Pactual.Text = Array(0)
O2actual.Text = Array(1)
COactual.Text = Array(2)
CO2actual.Text = Array(3)
P25actual.Text = Array(4)
P10actual.Text = Array(5)
txtUpdate.Text = Array(6)
End Function
Sub numberValidate()
Try
If (CDbl(txtPmax.Text) < CDbl(txtPmin.Text) Or (CDbl(txtO2max.Text) < CDbl(txtO2min.Text))) Then
MsgBox("Error. Must be numbers or Max < Min")
End If
Catch ex As Exception
MsgBox("Error. Must be numbers or Max < Min")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static bFlash As Boolean
receivedData = ReceiveSerialData()
If receivedData IsNot Nothing Then
txtUpdate.Text = receivedData
' Warning in GUI
Dim bWar As Boolean = receivedData.Contains("--Pressure not OK--" Or "--CO2 not OK--" Or "--O2 not OK--")
If receivedData.Contains("--Pressure not OK--" Or "--CO2 not OK--" Or "--O2 not OK--") Then
bFlash = Not bFlash
If bFlash Then
txtUpdate.BackColor = Color.FromArgb(255, 0, 0)
Else
txtUpdate.BackColor = Color.FromArgb(255, 255, 255)
End If
Else
txtUpdate.BackColor = Color.FromArgb(255, 0, 255)
End If
If receivedData.Contains("--Condition: Normal--") Then
txtUpdate.BackColor = Color.FromArgb(255, 255, 255)
End If
End If
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim writeText As String
writeText = "<" & CDbl(txtPmax.Text).ToString("00.0") & CDbl(txtPmin.Text).ToString("00.0") & CInt(txtO2max.Text).ToString("00") & CInt(txtO2min.Text).ToString("00") & CInt(txtCO2.Text).ToString("0000") & ">"
txtUpdate.Text = writeText
SerialPort1.Write(writeText)
End Sub
This is the first time that I have ever worked with networking in a program control webrelay. I was able to write my program with success... or so I thought. A couple of days ago I had a device drop off the network and my program "locked up". I know it did not truly lock up. I did some debugging and found out that what is happening is that when the tcpclient throws an exception, it just stops running any code after it. This causes my program to stop updating because of a timer that is never restarted and I con't control analog Outputs.
Public Class ControlPanelX317
Private SQL As New SQLControl
Private Sub ControlPanelX317_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadControlsX317()
End Sub
'Dislay Conrol
'__________________________________________________________________________________________________________________________________________________________________________
Private Sub LoadControlsX317()
Dim loadqry As String = "SELECT * FROM controlsX317 WHERE controlsX317.ValueVoltageID = '" & 1 & "' "
Dim SQLCmd As New SqlCommand(loadqry, Sql.SQLCon)
If Sql.SQLCon.State = ConnectionState.Closed Then Sql.SQLCon.Open()
Dim reader As SqlDataReader = SQLCmd.ExecuteReader
While reader.Read = True
txt_S1_VolueVoltage.Text = reader("S1VolueVoltage")
txt_S2_VolueVoltage.Text = reader("S2VolueVoltage")
txt_S3_VolueVoltage.Text = reader("S3VolueVoltage")
txt_S4_VolueVoltage.Text = reader("S4VolueVoltage")
End While
SQLCmd.Dispose()
reader.Close()
Sql.SQLCon.Close()
End Sub
Private Sub btn_Save_ValueVoltage_Click(sender As Object, e As EventArgs) Handles btn_Save_ValueVoltage.Click
If txt_S1_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S1_VolueVoltage.Clear()
Exit Sub
End If
If txt_S2_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S2_VolueVoltage.Clear()
Exit Sub
End If
If txt_S3_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S3_VolueVoltage.Clear()
Exit Sub
End If
If txt_S4_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S4_VolueVoltage.Clear()
Exit Sub
End If
If txt_S1_VolueVoltage.Text <> "" Then
Dim UpdateValueVoltage As String = "UPDATE controlsX317 SET S1VolueVoltage='" & txt_S1_VolueVoltage.Text & "', S2VolueVoltage='" & txt_S2_VolueVoltage.Text & "',
S3VolueVoltage='" & txt_S3_VolueVoltage.Text & "', S4VolueVoltage='" & txt_S4_VolueVoltage.Text & "'
WHERE ValueVoltageID ='" & 1 & "' "
If SQL.DataUpdate(UpdateValueVoltage) = 0 Then
MsgBox("The Sysytem could not be found!!! ")
Else
MsgBox("VolueVoltage successfully changed")
End If
Else
MsgBox("You must restart a Sysytem")
End If
End Sub
Private Sub btn_S1_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S1_SetVoltage.Click
lbl_S1_AnalogOutput.Text = Val(txt_S1_VolueVoltage.Text) * Val(txt_S1_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S2_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S2_SetVoltage.Click
lbl_S2_AnalogOutput.Text = Val(txt_S2_VolueVoltage.Text) * Val(txt_S2_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S3_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S3_SetVoltage.Click
lbl_S3_AnalogOutput.Text = Val(txt_S3_VolueVoltage.Text) * Val(txt_S3_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S4_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S4_SetVoltage.Click
lbl_S4_AnalogOutput.Text = Val(txt_S4_VolueVoltage.Text) * Val(txt_S4_ControlViltage.Text / 100) & "V"
End Sub
'End Display Control
'_________________________________________________________________________________________________________________________________________________________________________
'Conection to WebRelay X317
'_________________________________________________________________________________________________________________________________________________________________________
Public Sub getWebRelayState()
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?noReply=0 HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
Dim ana(4) As Integer
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
Else
inputState.Text = "OFF"
End If
End If
'Close the connection
tcpClient.Close()
End If
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub sendRequest(ByVal val As String)
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
'Disable the timer
TimerRelayRefresh.Enabled = False
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
MsgBox("connection successful")
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?relayState=1 HTTP/1.1<CR><LF>" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==<CR><LF><CR><LF>" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
End If
Else
inputState.Text = "OFF"
End If
End If
'Enable the timer
TimerRelayRefresh.Enabled = True
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub btn_ControlsX317_On_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_On.Click
sendRequest("1")
End Sub
Private Sub btn_ControlsX317_Off_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_Off.Click
sendRequest("0")
End Sub
Private Sub btn_ControlsX317_PULSE_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_PULSE.Click
sendRequest("2")
End Sub
'End Conetion
'_________________________________________________________________________________________________________________________________________________________________________
End Class
For some reason while I call a specific form in my program it comes up with
An unhandled exception of type 'System.InvalidOperationException' occurred in CinemaBooking2.exe
Additional information: An error occurred creating the form. See Exception.InnerException for details. The error is: Conversion from string "" to type 'Integer' is not valid.
But I'm not sure why. This only suddenly started happening and I'm not sure if it's visual studio messing up or me.
This is the form it is trying to load:
Imports System.IO
Public Class MainMenu2
Dim intChildren As Integer = 0
Dim intStandard As Integer = 0
Dim intOAP As Integer = 0
Public intTotal As Integer = 0
Dim Reader As StreamReader
Dim Writer As StreamWriter
Dim booAdmin As Boolean
Private Sub BtnComingSoon_Click(sender As Object, e As EventArgs) Handles BtnComingSoon.Click
Me.Visible = False
frmComingSoon.Visible = True
End Sub
Private Sub BtnEdit_Click(sender As Object, e As EventArgs)
Me.Hide()
FrmNowShowing.Show()
End Sub
Private Sub FrmMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Reader = New StreamReader("NowShowing.txt")
LblShowing1.Text = ("Now showing: " & Reader.ReadLine)
LblShowing2.Text = ("Now showing: " & Reader.ReadLine)
Reader.Close()
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
If booAdmin = False Then
BtnRefresh.Hide()
BtnEdit.Hide()
End If
End Sub
Private Sub BtnBook_Click(sender As Object, e As EventArgs) Handles BtnBook.Click
Me.Hide()
FrmBookings.Show()
End Sub
Private Sub CmbChildren_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbChildren.SelectedIndexChanged
intStandard = CInt(CmbStandard.Text) 'Code for standard combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
Private Sub CmbStandard_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles CmbStandard.SelectedIndexChanged
intStandard = CInt(CmbStandard.Text) 'Code for standard combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
Private Sub CmbOAP_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles CmbOAP.SelectedIndexChanged
intOAP = CInt(CmbOAP.Text) 'Code for OAP combo box
intTotal = intChildren + intStandard + intOAP
LblTotal.Text = ("Total: £" & (intChildren * 3.5) + (intStandard * 5.95) + (intOAP * 4.95) & " for " & intTotal & " People.")
Reader.Close()
If intTotal > 0 And intTotal <= 100 Then
BtnBook.Enabled = True
Else
BtnBook.Enabled = False
End If
Reader = New StreamReader("Settings.txt")
booAdmin = Reader.ReadLine
Reader.Close()
Writer = New StreamWriter("Settings.txt")
Writer.WriteLine(booAdmin)
Writer.WriteLine(intTotal)
Writer.Close()
End Sub
End Class
This error only appears for this form and no others, so I am unsure of if it is something to do with the form, or if the form has corrupted in some way.
Reader.ReadLine returns strings. I see several places in your code where you are trying to directly assign string values to variables that are not strings. for example:
booAdmin = Reader.ReadLine
This should probably be:
booAdmin = Boolean.Parse(Reader.ReadLine)
Any place where you are trying to read an integer should be:
someIntegerVariable = Integer.Parse(Reader.Readline)
If you want to be even more same, use TryParse instead of Parse, but that will have slightly different semantics.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm writing some code for a calculator and I keep getting this error. I have the math functions in another class but the variables from form1 are not accessible. Below is my code.
I've also tried changing my Dim variables to public but that also doesn't work.
Public Class Form1
'create a value to keep track of whether the calculation is complete so the calculator can revert to zero for new calculations
Dim state As Integer
'create values to store information on numbers and signs entered as well as the answer returned
Dim one As Double
Dim two As Double
Dim ans As Double
Dim sign As Char
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'when "Return" or "Enter" Key is selected button 15 is clicked (seems to only work when textbox selected????)
Me.AcceptButton = Button15
'change the title of the form
Me.Text = "Simple Calculator"
'label the buttons logically
Button1.Text = "1"
Button2.Text = "2"
Button3.Text = "3"
Button4.Text = "4"
Button5.Text = "5"
Button6.Text = "6"
Button7.Text = "7"
Button8.Text = "8"
Button9.Text = "9"
Button10.Text = "0"
Button11.Text = "+"
Button12.Text = "-"
Button13.Text = "X"
Button14.Text = "/"
Button15.Text = "Calc"
Button16.Text = "About Me"
Button17.Text = "Clear"
'allows form to revcieve key events
Me.KeyPreview = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'create action when button 1 is clicked
'if state is 1 then previous calculation was solved, then clear textbox to allow for new input
If state = 1 Then
TextBox1.Text = ""
'insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
'return state of calculator to zero to designate that calculation has NOT been solved
state = 0
Else
'else insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
End If
End Sub
' the above function for each numbered button
Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
state = 0
Else
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
state = 0
Else
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
state = 0
Else
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
End If
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
state = 0
Else
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
End If
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
state = 0
Else
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
End If
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
state = 0
Else
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
End If
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
state = 0
Else
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
End If
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
state = 0
Else
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
End If
End Sub
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
state = 0
Else
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
End If
End Sub
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
'create an action for when addition button is clicked
Try
'when button is clicked dim sign and text in textbox
sign = "+"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
'repeat the above action for remainder of arithmic functions
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Try
'when button is clicked dim sign and text in textbox
sign = "-"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Try
sign = "*"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Try
sign = "/"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
'run functions based on sign stored during calculation
Try
two = TextBox1.Text
If sign = "+" Then
Calculator2.Math.add()
ElseIf sign = "-" Then
Calculator2.Math.minus()
ElseIf sign = "*" Then
Calculator2.Math.multiply()
ElseIf sign = "/" Then
Calculator2.Math.divide()
End If
'if user attempts to divide by zero return divide by zero error in textbox
If TextBox1.Text = "Infinity" Then
TextBox1.Text = "Divide by Zero Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End If
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
'create message box that provides information about author
Dim msg = "Student Name: Emily Wong" & vbCrLf & "Student Number: 0692740" ' Define the message you want to see inside the message box.
Dim title = "About Me" ' Define a title for the message box.
Dim style = MsgBoxStyle.OkOnly ' make an ok button for the msg box
Dim response = MsgBox(msg, style, title)
End Sub
Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
'create a clear button to clear textboxes when clicked and reset state of calculator
TextBox1.Text = ""
state = 0
End Sub
And this is my other class
Public Class Math
Inherits Form1
'create funtions for add,sub, multiply, and divide features
Sub add()
ans = one + two 'creates calculation of the entered numbers
TextBox1.Text = ans 'returns answer into the textbox
state = 1 'returns state to 1 to show that calculation has occured
End Sub
Sub minus()
ans = one - two
TextBox1.Text = ans
state = 1
End Sub
Sub multiply()
ans = one * two
TextBox1.Text = ans
state = 1
End Sub
Sub divide()
ans = one / two
TextBox1.Text = ans
state = 1
End Sub
End Class
state is a private variable in Form1. You can't access from code outside of Form1. Your Math class cannot reference state. Remove the calls to state from the Math class code. An outside class should not be changing the state of another object in anycase.
Try this instead:
Public Class accounting
Dim Operand1 As Double
Dim Operand2 As Double
Dim [Operator] As String
These are the button from 1 - 0
Private Sub Button6_Click_1(sender As Object, e As EventArgs) Handles Button9.Click, Button8.Click, Button7.Click, Button6.Click, Button5.Click, Button4.Click, Button19.Click, Button12.Click, Button11.Click, Button10.Click
txtans.Text = txtans.Text & sender.text
End Sub
This button is for period/point
Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
If InStr(txtans.Text, ".") > 0 Then
Exit Sub
Else
txtans.Text = txtans.Text & "."
End If
End Sub
This button is for clear or "C" in calculator
Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
txtans.Text = ""
End Sub
These are for add,subtract,divide, and multiply
Private Sub Buttonadd_Click(sender As Object, e As EventArgs) Handles Button13.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "+"
End Sub
Private Sub Buttondivide_Click(sender As Object, e As EventArgs) Handles Button15.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "-"
End Sub
Private Sub Buttonsubtract_Click(sender As Object, e As EventArgs) Handles Button16.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "*"
End Sub
Private Sub Buttonmultiply_Click(sender As Object, e As EventArgs) Handles Button14.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "/"
End Sub
This button is for "=" sign
Private Sub Buttoneequal_Click(sender As Object, e As EventArgs) Handles Button17.Click
Dim Result As Double
Operand2 = Val(txtans.Text)
'If [Operator] = "+" Then
' Result = Operand1 + Operand2
'ElseIf [Operator] = "-" Then
' Result = Operand1 - Operand2
'ElseIf [Operator] = "/" Then
' Result = Operand1 / Operand2
'ElseIf [Operator] = "*" Then
' Result = Operand1 * Operand2
'End If
Select Case [Operator]
Case "+"
Result = Operand1 + Operand2
txtans.Text = Result.ToString("#,###.00")
Case "-"
Result = Operand1 - Operand2
txtans.Text = Result.ToString("#,###.00")
Case "/"
Result = Operand1 / Operand2
txtans.Text = Result.ToString("#,###.00")
Case "*"
Result = Operand1 * Operand2
txtans.Text = Result.ToString("#,###.00")
End Select
txtans.Text = Result.ToString("#,###.00")
End Sub
This button is for backspace effect.
Private Sub Buttondel_Click(sender As Object, e As EventArgs) Handles Button21.Click
If txtans.Text < " " Then
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1 + 1)
Else
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1)
End If
End Sub
Note that "txtans.text" is the textbox where the user inputs and where the output shows.
I'm making a program that will remove the pain of hex editing an old DOS game (sensible world of soccer).
The program removes the limit of the number of players you can purchase (5), removes the maximum number of seasons you can compete for (20).
I'm trying to make it so you can edit your transfer budget too but i'm getting a Arithmetic operation resulted in an overflow. error when i run the code select the 50million option.
Here is the full code for my program (the transfer limit & maximum season limit both work):
Imports System.IO
Public Class Swos_Editor_2013
Dim transferbudget As String
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'#########
'#WARNING#
'#########
'Dim answer As DialogResult
'answer = MessageBox.Show("Make a Backup of your career file then click OK to proceed. I take no responsibility for damaged career files",
' "*PLEASE READ BEFORE PROCEEDING*", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
'##########################
'#Progress bar set options#
'##########################
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 2
ProgressBar1.Value = 0
'##################
'#tool tip options#
'##################
Dim toolTip1 As New ToolTip
toolTip1.AutoPopDelay = 5000
toolTip1.InitialDelay = 1000
toolTip1.ReshowDelay = 500
ToolTip1.ShowAlways = True
'###################################
'#Open Swos career file for editing#
'###################################
Me.OpenFileDialog1.InitialDirectory = "c:\"
Me.OpenFileDialog1.Title = "Select Career File for editing"
Me.OpenFileDialog1.DefaultExt = "*.car"
Me.OpenFileDialog1.FileName = ""
Me.OpenFileDialog1.Filter = "Career File(*.car)|*.car"
Me.OpenFileDialog1.Multiselect = False
'###################
'#OK button pressed#
'###################
If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
'##############################
'#increase progress bar to 50%#
'##############################
If ProgressBar1.Value < ProgressBar1.Maximum Then
ProgressBar1.Value += 1
End If
'################
'#Enable buttons#
'################
btn_save.Enabled = True
btn_trans_limit.Enabled = True
btn_career_limit.Enabled = True
cb_combo.Enabled = True
End If
End Sub
'#######################
'#Enable combo box drop#
'#######################
Private Sub cb_combo_CheckedChanged(ByVal sender As Object, e As EventArgs) Handles cb_combo.CheckedChanged
ComboBox1.Enabled = True
End Sub
'########################
'#Select Transfer Budget#
'########################
Private Sub ComboBox1_DropDownClosed(ByVal sender As Object, e As EventArgs) Handles ComboBox1.DropDownClosed
Select Case ComboBox1.SelectedItem
Case Is = "-£10 million (are you crazy CHALLENGE)"
transferbudget = "100"
Case Is = "-£2 million (mid level CHALLENGE)"
transferbudget = "200"
Case Is = "-£500k (lower league CHALLENGE)"
transferbudget = "500"
Case Is = "£500k (tough)"
transferbudget = "05"
Case Is = "£5 million"
transferbudget = "5"
Case Is = "£10 million"
transferbudget = "10"
Case Is = "£25 million"
transferbudget = "25"
Case Is = "£50 million"
transferbudget = "50000000"
Case Is = "£99 million"
transferbudget = "999"
End Select
End Sub
'#######################################
'#exit if EXIT is clicked from dropdown#
'#######################################
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
'#######################
'#Not got a bloody clue#
'#######################
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
'##################################################################
'#Apply changes made to drop down box AND radio button IF selected#
'##################################################################
Public Sub SaveChanges()
Dim amount As Integer
Dim fpath As String = OpenFileDialog1.FileName
Using stream = New FileStream(fpath, FileMode.Open, FileAccess.ReadWrite)
Dim result As Integer = 0
Dim buffer As Byte() = New Byte(3) {}
stream.Position = 54748
If (stream.Read(buffer, 0, 4) <> 4) Then
Throw New Exception(("Didn't read 4 bytes when it should have: " _
+ (result + "bytes read")))
End If
stream.Position = &HD5DC
buffer = BitConverter.GetBytes(amount)
stream.Write(buffer, 0, 4)
stream.Position = &HD880
If btn_career_limit.Checked Then
stream.WriteByte(0)
Else
stream.WriteByte(1)
End If
stream.Position = &HD5C4
If btn_trans_limit.Checked Then
stream.WriteByte(&HFF)
Else
stream.WriteByte(0)
End If
'stream.Write(buffer, 0, 4)
'stream.Position = &HD5DC
'If testbutton.Checked Then
' stream.WriteByte("3B9AC9FF")
'End If
**If cb_combo.Checked = True Then
stream.Position = &HD5DC
stream.WriteByte(transferbudget) ######this is where i get the overflow error#####**
End If
End Using
End Sub
'###############################################
'#Save above changes & set progress bar to 100%#
'###############################################
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
SaveChanges()
If ProgressBar1.Value < ProgressBar1.Maximum Then
ProgressBar1.Value += 1
End If
End Sub
'#########################################################################################################################################
'# TOOL TIP (MOUSE HOVER) #
'# #
Private Sub btn_trans_limit_CheckedChanged(sender As Object, e As EventArgs) Handles btn_trans_limit.MouseHover
'#
ToolTip1.SetToolTip(btn_trans_limit, "Removes 5 player transfer limit") '#
End Sub
Private Sub btn_career_limit_CheckedChanged(sender As Object, e As EventArgs) Handles btn_career_limit.MouseHover '#
'# '#
ToolTip1.SetToolTip(btn_career_limit, "Removes 20 season limit") '#
End Sub
Private Sub ComboBox1_MouseHover(sender As Object, e As EventArgs) Handles ComboBox1.MouseHover '#
'# '#
ToolTip1.SetToolTip(ComboBox1, "Select Transfer Budget") '#
End Sub
Private Sub btn_save_MouseHover(sender As Object, e As EventArgs) Handles btn_save.MouseHover '#
'# '#
ToolTip1.SetToolTip(btn_save, "Save changes to your career file")
End Sub
Private Sub cb_combo_MouseHover(sender As Object, e As EventArgs) Handles cb_combo.MouseHover '#
'# '#
ToolTip1.SetToolTip(cb_combo, "tick if you want to edit transfer budget") '#
End Sub
'#########################################################################################################################################
End Class
Any help would be greatly appreciated.
You are passing a String (transferbudget) into the FileStream.WriteByte method. The WriteByte method takes a Byte, not a String. If you had Option Strict On, as you should, this would result in a compile error. However, since you have Option Strict Off, it allows you to compile and just automatically inserts the type conversion from String to Byte for you. The type conversion operation will throw an overflow exception if the value in the string is outside of the minimum and maximum value of a Byte (0 - 255). Here's the code where you set the transferbudget variable:
Select Case ComboBox1.SelectedItem
Case Is = "-£10 million (are you crazy CHALLENGE)"
transferbudget = "100"
Case Is = "-£2 million (mid level CHALLENGE)"
transferbudget = "200"
Case Is = "-£500k (lower league CHALLENGE)"
transferbudget = "500" 'GAH!
Case Is = "£500k (tough)"
transferbudget = "05"
Case Is = "£5 million"
transferbudget = "5"
Case Is = "£10 million"
transferbudget = "10"
Case Is = "£25 million"
transferbudget = "25"
Case Is = "£50 million"
transferbudget = "50000000" 'GAH!
Case Is = "£99 million"
transferbudget = "999" 'GAH!
End Select
As you can see, there are several values there that are greater than 255.