Splitting data received from Arduino - vb.net

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

Related

Program drops com port while receiving data from arduino VB.net

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.

SSL/TLS connection not working in webclient after being in background

So if I use my program normally no error occurs. But if it is in background for longer time and I use the webclient to visit a web address it immidiately throws could not create a SSL/TLS secure channel error but if I try again the error dissapears. I already set the TLS to 1.2 and expect100continue to false.
Imports System.Net
Imports System.Text.RegularExpressions
Public Class CinemaLinker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MaximizeBox = False
If Not HaveInternetConnection() Then
MessageBox.Show("Warning: no internet connection!")
End If
ServicePointManager.Expect100Continue = False
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
End Sub
Public Property TextFromBox As String
Public Property StatusLink As String
Private Client As New WebClient
Private GoogleSearch = "****"
Private BingSearch = "*****"
Private AskSearch = "*****"
Private Sub Search() Handles Button1.Click
Cursor.Current = Cursors.WaitCursor
TextFromBox = RichTextBox1.Text
If Button3.Enabled And Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please choose a category!")
Exit Sub
End If
If TextFromBox.Contains("Type movie or tv series name here") Or String.IsNullOrEmpty(TextFromBox) Or String.IsNullOrWhiteSpace(TextFromBox) Then
Cursor.Current = Cursors.[Default]
If Not Button3.Enabled Then
MessageBox.Show("Please type the name of the movie!")
Exit Sub
End If
If Not Button4.Enabled Then
If Not (String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E")) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Episode number missing!")
Exit Sub
End If
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series! Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Please type the name of the tv series!")
Exit Sub
End If
End If
If Not Button4.Enabled Then
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Or RichTextBox3.Text.Contains("E") Then
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season and episode numbers missing!")
Exit Sub
End If
Cursor.Current = Cursors.[Default]
MessageBox.Show("Episode number missing!")
Exit Sub
ElseIf String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Or RichTextBox2.Text.Contains("S") Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Season number missing!")
Exit Sub
End If
End If
If Not HaveInternetConnection() Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("No internet connection!")
Exit Sub
End If
Dim ImdbURL As String = getIMDbUrl(TextFromBox)
If Not ImdbURL.Contains("******") And Not Button3.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " movie"
If Not ImdbURL.Contains("***") And Not Button3.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name!")
Exit Sub
End If
End If
If Not ImdbURL.Contains("***") And Not Button4.Enabled Then
ImdbURL = getIMDbUrl(TextFromBox) + " TV series"
If Not ImdbURL.Contains("****") And Not Button4.Enabled Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name!")
Exit Sub
End If
End If
Dim LinkFinal As String = (GetLink(ImdbURL))
If String.IsNullOrEmpty(LinkFinal) Or String.IsNullOrWhiteSpace(LinkFinal) Then
Cursor.Current = Cursors.[Default]
Exit Sub
End If
Clipboard.SetText(LinkFinal)
MessageBox.Show("Link in clipboard. Paste it into desired browser!")
TextFromBox = String.Empty
StatusLink = "0"
Cursor.Current = Cursors.[Default]
End Sub
Public Function HaveInternetConnection() As Boolean
Dim result As Boolean
Try
result = My.Computer.Network.Ping("www.google.com")
Catch ex As Exception
result = False
End Try
Return result
End Function
Private Function GetIP() As String
Return Client.DownloadString("https://api.ipify.org").ToString()
End Function
Private Function matchAll(ByVal regex As String, ByVal html As String, ByVal Optional i As Integer = 1) As ArrayList
Dim list As ArrayList = New ArrayList()
For Each m As Match In New Regex(regex, RegexOptions.Multiline).Matches(html)
list.Add(m.Groups(i).Value.Trim())
Next
Return list
End Function
Private Function getIMDbUrl(MovieName As String, Optional searchEngine As String = "google") As String
Dim address As String = GoogleSearch + MovieName
If searchEngine.ToLower().Equals("bing") Then
address = BingSearch + MovieName
End If
If searchEngine.ToLower().Equals("ask") Then
address = AskSearch + MovieName
End If
Dim html As String = Client.DownloadString(address)
Dim arrayList As ArrayList = matchAll("<a href=""(*****\d{7}/)"".*?>.*?</a>", html, 1)
If arrayList.Count > 0 Then
Return CStr(arrayList(0))
ElseIf searchEngine.ToLower().Equals("google") Then
Return getIMDbUrl(MovieName, "bing")
ElseIf searchEngine.ToLower().Equals("bing") Then
Return getIMDbUrl(MovieName, "ask")
Else
Return String.Empty
End If
End Function
Private Function GetLink(ImdbURL As String) As Object
Dim ID = ImdbURL.Replace("*****/", "")
ID = ID.Replace("/", "")
Dim result As Object
If StatusLink = "1" Then
Cursor.Current = Cursors.[Default]
Exit Function
ElseIf Not Button4.Enabled Then
Dim SeasonNumber As String = "&s=" + RichTextBox2.Text
Dim EpisodeNumber As String = "&e=" + RichTextBox3.Text
Dim TVSeasonNumber As String = "&tv=1" + SeasonNumber
If Not Client.DownloadString("*****/" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " TV series")
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("*****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("TV series not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address As String = "******" & ID & TVSeasonNumber & "&ip=" & GetIP()
Dim token As String = Client.DownloadString(address)
result = "*****" & ID & TVSeasonNumber & EpisodeNumber & "&ticket=" & token
Return result.ToString
Exit Function
End If
ElseIf Not Button3.Enabled Then
If Client.DownloadString("****" & ID).Contains(">Episode Guide<") Then
ImdbURL = getIMDbUrl(TextFromBox + " movie",)
StatusLink = "1"
If String.IsNullOrEmpty(ImdbURL) Or String.IsNullOrWhiteSpace(ImdbURL) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
ID = ImdbURL.Replace("****", "")
ID = ID.Replace("/", "")
result = (GetLink(ImdbURL))
If String.IsNullOrEmpty(result) Or String.IsNullOrWhiteSpace(result) Then
Cursor.Current = Cursors.[Default]
MessageBox.Show("Movie not found! Please add the year in the name or check category!")
result = String.Empty
Exit Function
Else
Return result.ToString()
result = String.Empty
Exit Function
End If
End If
Else
Dim address2 As String = "****" & ID & "&ip=" & GetIP()
Dim token2 As String = Client.DownloadString(address2)
result = "****" & ID & "&ticket=" & token2
Return result.ToString
result = String.Empty
Exit Function
End If
End If
#Disable Warning BC42105 ' Function doesn't return a value on all code paths
End Function
Private Sub RichTextBox1_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox1.GotFocus
If RichTextBox1.Text.Contains("Type movie or tv series name here") Then RichTextBox1.Text = String.Empty
End Sub
Private Sub RichTextBox2_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox2.GotFocus
If RichTextBox2.Text.Contains("S") Then RichTextBox2.Text = String.Empty
End Sub
Private Sub RichTextBox3_MouseClick(sender As Object, e As EventArgs) Handles RichTextBox3.GotFocus
If RichTextBox3.Text.Contains("E") Then RichTextBox3.Text = String.Empty
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.Enabled = False
Button4.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = False
RichTextBox3.Enabled = False
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Button4.Enabled = False
Button3.Enabled = True
RichTextBox1.Enabled = True
RichTextBox2.Enabled = True
RichTextBox3.Enabled = True
End Sub
Private Sub RichTextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox2.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox3.KeyPress
If Char.IsLetter(e.KeyChar) Then
e.Handled = True
End If
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
End Sub
Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If CType(e, KeyPressEventArgs).KeyChar = vbCr Then
Search()
End If
If Char.IsUpper(e.KeyChar) Then e.KeyChar = Char.ToLower(e.KeyChar)
End Sub
Private Sub RichTextBox1_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox1.LostFocus
If String.IsNullOrEmpty(RichTextBox1.Text) Or String.IsNullOrWhiteSpace(RichTextBox1.Text) Then
RichTextBox1.Text = "Type movie or tv series name here..."
End If
End Sub
Private Sub RichTextBox2_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox2.LostFocus
If String.IsNullOrEmpty(RichTextBox2.Text) Or String.IsNullOrWhiteSpace(RichTextBox2.Text) Then
RichTextBox2.Text = "S:"
End If
End Sub
Private Sub RichTextBox3_Lostfocus(sender As Object, e As EventArgs) Handles RichTextBox3.LostFocus
If String.IsNullOrEmpty(RichTextBox3.Text) Or String.IsNullOrWhiteSpace(RichTextBox3.Text) Then
RichTextBox3.Text = "E:"
End If
End Sub
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox2_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox2.TextChanged
StatusLink = "0"
End Sub
Private Sub RichTextBox3_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox3.TextChanged
StatusLink = "0"
End Sub
End Class
all of the ***** are https website addresses.
Tried switching the Net version to 4.7. Did not help. It is also legal in my country to stream (interior minister dropped a bomb on the DMCA here lol) and this is streaming only. The code is not operational so i had not given you anything dangerous if it is illegal in yours.

Datagridview filtering by TextBox or CheckBox

Here is my code:
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim socketz As New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP)
Dim bytedata(4096) As Byte
Dim myip As IPAddress
Dim started As Boolean = True
Dim sizediff As Size
Dim formloaded As Boolean = False
Dim FilterIPAddress As New IPAddress(0)
Dim FilterIP As Boolean
Dim mycomputerconnections() As Net.NetworkInformation.NetworkInterface
'datagridview1 Update stuff
Dim stringz As String = ""
Dim Typez As String = ""
Dim ipfrom As IPAddress
Dim ipto As IPAddress
Dim destinationport As String = ""
Dim sourceport As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sizediff.Height = Me.Height - DataGridView1.Height
sizediff.Width = Me.Width - DataGridView1.Width
formloaded = True
mycomputerconnections = Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces
For i = 0 To mycomputerconnections.Length - 1
Combobox1.Items.Add(mycomputerconnections(i).Name)
Next
End Sub
Private Sub OnReceive(ByVal asyncresult As IAsyncResult)
If started = True Then
'Get Length of packet (including header)
Dim readlength As UInteger = BitConverter.ToUInt16(Byteswap(bytedata, 2), 0)
sourceport = BitConverter.ToUInt16(Byteswap(bytedata, 22), 0)
destinationport = BitConverter.ToUInt16(Byteswap(bytedata, 24), 0)
'Get Protocol Type
If bytedata(9) = 6 Then
Typez = "TCP"
ElseIf bytedata(9) = 17 Then
Typez = "UDP"
Else
Typez = "???"
End If
'Get IP from and to
ipfrom = New IPAddress(BitConverter.ToUInt32(bytedata, 12))
ipto = New IPAddress(BitConverter.ToUInt32(bytedata, 16))
'If this is a packet to/from me and not from myself then...
If (ipfrom.Equals(myip) = True Or ipto.Equals(myip) = True) And ipto.Equals(ipfrom) = False Then
If FilterIP = False Or (FilterIP = True And (FilterIPAddress.Equals(ipfrom) Or FilterIPAddress.Equals(ipto))) Then
'Fix data
stringz = ""
For i = 26 To readlength - 1
If Char.IsLetterOrDigit(Chr(bytedata(i))) = True Then
stringz = stringz & Chr(bytedata(i))
Else
stringz = stringz & "."
End If
Next
'Put data to DataGridView, since it's on a different thread now, invoke it
DataGridView1.Invoke(New MethodInvoker(AddressOf datagridview1Update))
End If
End If
End If
'Restart the Receiving
socketz.BeginReceive(bytedata, 0, bytedata.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
End Sub
Private Sub datagridview1Update()
'Remove rows if there are too many
If DataGridView1.Rows.Count > 9 Then
DataGridView1.Rows.RemoveAt(0)
End If
DataGridView1.Rows.Add()
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(0).Value = ipfrom.ToString 'From Column, size at 125
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(1).Value = ipto.ToString 'To Column, size at 125
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(2).Value = destinationport.ToString
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(3).Value = sourceport.ToString
End Sub
Private Function Byteswap(ByVal bytez() As Byte, ByVal index As UInteger)
Dim result(1) As Byte
result(0) = bytez(index + 1)
result(1) = bytez(index)
Return result
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If started = True Then
Button1.Text = "Start"
started = False
Else
Button1.Text = "Stop"
started = True
End If
End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
If formloaded = True Then
DataGridView1.Size = Me.Size - sizediff
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Combobox1.SelectedIndexChanged
For i = 0 To mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses.Count - 1
If mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses(i).Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
myip = mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses(i).Address
BindSocket()
End If
Next
End Sub
Private Sub BindSocket()
Try
socketz.Bind(New IPEndPoint(myip, 0))
socketz.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, True)
Dim bytrue() As Byte = {1, 0, 0, 0}
Dim byout() As Byte = {1, 0, 0, 0}
socketz.IOControl(IOControlCode.ReceiveAll, bytrue, byout)
socketz.Blocking = False
ReDim bytedata(socketz.ReceiveBufferSize)
socketz.BeginReceive(bytedata, 0, bytedata.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
Combobox1.Enabled = False
Catch ex As Exception
Combobox1.BackColor = Color.Red
End Try
End Sub
End Class
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
If TextBox1.Text <> "" And TextBox1.Text IsNot Nothing Then
FilterIPAddress = IPAddress.Parse(TextBox1.Text)
FilterIP = True
TextBox1.BackColor = Color.LimeGreen
Else
FilterIP = False
TextBox1.BackColor = Color.White
End If
Catch ex As Exception
FilterIP = False
TextBox1.BackColor = Color.White
End Try
End Sub
I'm trying to filter my DataGridView to only show the TextBox1's value of the sourceport column.

not accessible in this context because it is 'Private' [closed]

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.

Arithmetic operation resulted in an overflow.

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.