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.
Related
Can I do this shorter from a single timer without needing 5 timers?
I can run it in a sub Timer1.Enabled = True, Timer1.Start () and can change according to preferences, timer2, timer3. so I want to do this to go shorter. I think I should have a case function, or something like that. how could i do it
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim strx As String
Dim stry As String
For i As Integer = 1 To 10
strx = TextBox1.Lines(i)
stry = TxtBoxIntDrawsY.Text
If stry.Contains(strx) = True Then
Exit For
RndTitaniumA1()
Else
Exit For
If TextBox4.Text = ("1") Then
BttRnd.PerformClick()
Else
RndTitaniumA2()
End If
End If
Next
Timer1.Stop()
Timer1.Enabled = False
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim strx As String
Dim stry As String
For i As Integer = 1 To 10
strx = TextBox1.Lines(i)
stry = TxtBoxIntDrawsY.Text
If stry.Contains(strx) = True Then
Exit For
RndTitaniumA1()
Else
Exit For
If TextBox4.Text = ("2") Then
BttRnd.PerformClick()
Else
RndTitaniumA3()
End If
End If
Next
Timer2.Stop()
Timer2.Enabled = False
End Sub
Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
Dim strx As String
Dim stry As String
For i As Integer = 1 To 10
strx = TextBox1.Lines(i)
stry = TxtBoxIntDrawsY.Text
If stry.Contains(strx) = True Then
Exit For
RndTitaniumA1()
Else
Exit For
If TextBox4.Text = ("3") Then
BttRnd.PerformClick()
Else
RndTitaniumA4()
End If
End If
Next
Timer3.Stop()
Timer3.Enabled = False
End Sub
Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
Dim strx As String
Dim stry As String
For i As Integer = 1 To 10
strx = TextBox1.Lines(i)
stry = TxtBoxIntDrawsY.Text
If stry.Contains(strx) = True Then
Exit For
RndTitaniumA1()
Else
Exit For
If TextBox4.Text = ("4") Then
BttRnd.PerformClick()
Else
RndTitaniumA5()
End If
End If
Next
Timer4.Stop()
Timer4.Enabled = False
End Sub
Private Sub Timer5_Tick(sender As Object, e As EventArgs) Handles Timer5.Tick
Dim strx As String
Dim stry As String
For i As Integer = 1 To 10
strx = TextBox1.Lines(i)
stry = TxtBoxIntDrawsY.Text
If stry.Contains(strx) = True Then
Exit For
RndTitaniumA1()
Else
Exit For
If TextBox4.Text = ("5") Then
BttRnd.PerformClick()
Else
MsgBox("")
End If
End If
Next
Timer5.Stop()
Timer5.Enabled = False
End Sub
Let's start with your answers to my questions.
Array indexes in .net start at zero. If you have 10 lines in your textbox, you will get an index out of range exception with For i As Integer = 1 To 10 because there is no index 10. The indexes run from 0 to 9. I still don't see how you are preventing the user from deleting a few lines.
It won't run because you have preceded the code with Exit For. When the code reaches that line it exits the For loop and goes immediately to TimerX.Stop().
Private Sub OpCode()
For i = 0 To 10
Exit For
MessageBox.Show(i.ToString)
Next
End Sub
The MessageBox in the above code will never be displayed. Even if you repositioned the Exit For, you have the exit in both the If block and the Else block so the code would only survive one iteration.
You still didn't answer if the code works as written or why you are using a For loop at all and leaving the loop on the first iteration. Also, the mysterious empty MsgBox and why there are 5 timers.
You can add a break point and step through your code.
Notice the Handles clause in the .Tick event. This event now handles all the Timers.
I used a Select Case as suggested by #preciousbetine in comments. Since a Timer is a component it has no Name property (what I would normally use in the Select Case) so, I used the Is operator. I could also have set the .Tag property for each Timer and used that. I left in the Exit For (repositioned) but be aware; you will only get a single iteration.
Calling an event in code can have unanticipated effects. I showed you how to move the code from the button click to a separate Sub and then call it from the .Click and your routine.
Private Sub AnyTimer_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick, Timer2.Tick, Timer3.Tick, Timer4.Tick, Timer5.Tick
Dim t As System.Windows.Forms.Timer = DirectCast(sender, System.Windows.Forms.Timer)
Dim strx As String
Dim stry As String
stry = TxtBoxIntDrawsY.Text
For i As Integer = 0 To 9
strx = TextBox1.Lines(i)
If stry.Contains(strx) = True Then
RndTitaniumA1()
Exit For
Else
Dim TextBox4Contents As String = ""
Select Case True
Case t Is Timer1
TextBox4Contents = "1"
Case t Is Timer2
TextBox4Contents = "2"
Case t Is Timer3
TextBox4Contents = "3"
Case t Is Timer4
TextBox4Contents = "4"
Case t Is Timer5
TextBox4Contents = "5"
End Select
If TextBox4.Text = TextBox4Contents Then
RndSub()
Else
Select Case True
Case t Is Timer1
RndTitaniumA2()
Case t Is Timer2
RndTitaniumA3()
Case t Is Timer3
RndTitaniumA4()
Case t Is Timer4
RndTitaniumA5()
Case t Is Timer5
MsgBox("") '???
Case Else
MessageBox.Show("Sender does not match any Timer")
Return
End Select
End If
Exit For
End If
Next
t.Stop()
t.Enabled = False
End Sub
Private Sub BttnRnd_Click(sender As Object, e As EventArgs) Handles BttnRnd.Click
RndSub()
End Sub
Private Sub RndSub()
'Your button code here
End Sub
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
First time posting here, although I'm a frequent visitor when I'm looking for answers. I am new to VB and programming.
My problem is this. I had this figured out in VBA, but I want to convert my "program" to a standalone executable with VB (using Visual Studio 2015)
I want to keep track of certain keypresses done on a textbox, and so far I figured out something that works, but it seems messy.
Can anyone think of a better way of doing
Public Class Form1
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : Label3.Text = Val(Label3.Text) + 1
Case "R" : Label4.Text = Val(Label4.Text) + 1
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in labels
WcountA = Convert.ToInt32(Label3.Text)
RcountA = Convert.ToInt32(Label4.Text)
Button1.Text = "Finish B"
Label5.Text = WcountA
Label7.Text = RcountA
TextBox1.Focus()
Label3.Text = ""
Label4.Text = ""
Case "Finish B" 'Finishes second count and stores in labels
WcountB = Convert.ToInt32(Label3.Text)
RcountB = Convert.ToInt32(Label4.Text)
With Button1
.Text = "Finished"
.Enabled = False
End With
Label6.Text = WcountB
Label8.Text = RcountB
Label3.Text = ""
Label4.Text = ""
WcountA = Label5.Text
RcountA = Label7.Text
WcountB = Label6.Text
RcountB = Label8.Text
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
End Select
End Sub
End Class
On the form I have the textbox that logs the keypress event, labels that increase by 1 with each specific keypess ("W" and "R"), a button that changes its function with each click(finish first count, finish second count) and some labels I had to use to store the first and second count for the final calculation.
Any suggestion will be appreciated.
Thanks in advance!
First of al, you need to take out the counters of the key pres handler like so;
Because they are gone every time the Button1_Click sub ends.
Public Class Form1
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : Label3.Text = Val(Label3.Text) + 1
Case "R" : Label4.Text = Val(Label4.Text) + 1
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in labels
WcountA = Convert.ToInt32(Label3.Text)
RcountA = Convert.ToInt32(Label4.Text)
Button1.Text = "Finish B"
Label5.Text = WcountA
Label7.Text = RcountA
TextBox1.Focus()
Label3.Text = ""
Label4.Text = ""
Case "Finish B" 'Finishes second count and stores in labels
WcountB = Convert.ToInt32(Label3.Text)
RcountB = Convert.ToInt32(Label4.Text)
With Button1
.Text = "Finished"
.Enabled = False
End With
Label6.Text = WcountB
Label8.Text = RcountB
Label3.Text = ""
Label4.Text = ""
WcountA = Label5.Text
RcountA = Label7.Text
WcountB = Label6.Text
RcountB = Label8.Text
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
End Select
End Sub
End Class
This is what I ended up doing, works better and looks cleaner. Thanks Lectere for pointing me to the right path!
Public Class Form1
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : lblWcount.Text = Val(lblWcount.Text) + 1
Case "R" : lblRcount.Text = Val(lblRcount.Text) + 1
Case Convert.ToChar(13) : Button1_Click(sender, e)
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in variables
If lblWcount.Text = vbNullString Then 'checks for empty values and treats them as 0
WcountA = 0
Else
WcountA = lblWcount.Text
End If
If lblRcount.Text = vbNullString Then 'checks for empty values and treats them as 0
RcountA = 0
Else
RcountA = lblRcount.Text
End If
Button1.Text = "Finish B"
lbl_1.Text = WcountA
lbl_2.Text = RcountA
TextBox1.Focus()
lblWcount.Text = vbNullString
lblRcount.Text = vbNullString
lblcount.Text = "Count B"
Case "Finish B" 'Finishes second count and stores results in variables
lblcount.Text = vbNullString
If lblWcount.Text = vbNullString Then
WcountB = 0
Else
WcountB = lblWcount.Text
End If
If lblRcount.Text = vbNullString Then
RcountB = 0
Else
RcountB = lblRcount.Text
End If
With Button1
.Text = "Reset"
End With
lbl_3.Text = WcountB
lbl_4.Text = RcountB
lblWcount.Text = vbNullString
lblRcount.Text = vbNullString
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
Button1.Focus()
Case "Reset" 'Resets values
Dim i As Integer
For i = 1 To 4 'clears labels that start with lbl_ (1 through 4)
Dim myLabel As Label = CType(Controls("lbl_" & i), Label)
myLabel.Text = vbNullString
Next
Initial() ' calls initial form state
End Select
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Initial() 'calls initial form state at load up
End Sub
Private Sub Initial() 'initial state sub
lblcount.Text = "Count A"
TextBox1.Focus()
Button1.Text = "Finish A"
End Sub
End Class
I managed to use loops for clearing labels, and also made pressing Enter during the KeyPress event be treated as a button click.
Loving this feeling of accomplishment when I finally figure something out on something new to me! Love pages like this one where one can learn so much!
Alright, so the program is set up where you have a set of radio buttons with 5 states, and another set of 5 with 5 capitals. There's a button which tells you if they match or not. However I have to do it a certain way where clicking a radio button assigns a variable to both 'strCapital' and 'strChoice' and you compare them to see if they match.
I've tried to figure everything out (since it sounds easy in theory) but I've hit a wall.
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Dim strCapital As String
Dim strChoice As String
Dim strLittleRock As String
Dim strSpringfield As String
Dim strFrankfort As String
Dim strSalem As String
Dim strMadison As String
Private Sub radArkansas_CheckedChanged(sender As Object, e As EventArgs) Handles radArkansas.CheckedChanged
strCapital = strLittleRock
End Sub
Private Sub radIllinois_CheckedChanged(sender As Object, e As EventArgs) Handles radIllinois.CheckedChanged
strCapital = strSpringfield
End Sub
Private Sub radSpringfield_CheckedChanged(sender As Object, e As EventArgs) Handles radSpringfield.CheckedChanged
strChoice = strSpringfield
End Sub
Private Sub btnVerify_Click(sender As Object, e As EventArgs) Handles btnVerify.Click
If strCapital = strChoice Then
lblMsg.Text = "Correct"
ElseIf strCapital <> strChoice Then
lblMsg.Text = "Incorrect"
End If
End Sub
Private Sub radLittleRock_CheckedChanged(sender As Object, e As EventArgs) Handles
radLittleRock.CheckedChanged
strChoice = strLittleRock
End Sub
End Class
EDIT: Also I forgot to mention the main problem which is always a bad thing. Basically whenever I run it and enter something incorrect (checking Arkansas and Springfield for example) it always says it's correct.
I did something similar... you can modify this code:
Private Sub btnAmIRight_Click(sender As Object, e As EventArgs) Handles btnAmIRight.Click
' displays if submission is correct
' declare variables
Dim strAmIRight As String
Dim dblMatch As Double
If rbtnAlabama.Checked = True And rbtnMontgomery.Checked = True Then
dblMatch = 1
ElseIf rbtnAlaska.Checked = True And rbtnJuneau.Checked = True Then
dblMatch = 1
ElseIf rbtnArizona.Checked = True And rbtnPhoenix.Checked = True Then
dblMatch = 1
ElseIf rbtnArkansas.Checked = True And rbtnLittleRock.Checked = True Then
dblMatch = 1
ElseIf rbtnCalifornia.Checked = True And rbtnSacramento.Checked = True Then
dblMatch = 1
ElseIf rbtnColorado.Checked = True And rbtnDenver.Checked = True Then
dblMatch = 1
ElseIf rbtnConnecticut.Checked = True And rbtnHartford.Checked = True Then
dblMatch = 1
ElseIf rbtnDelaware.Checked = True And rbtnDover.Checked = True Then
dblMatch = 1
ElseIf rbtnFlorida.Checked = True And rbtnTallahassee.Checked = True Then
dblMatch = 1
ElseIf rbtnGeorgia.Checked = True And rbtnAtlanta.Checked = True Then
dblMatch = 1
Else
dblMatch = 0
End If
' assign code to variable
If dblMatch = 1 Then
strAmIRight = "Correct"
ElseIf dblMatch = 0 Then
strAmIRight = "Try Again"
End If
' display result
lblResult.Text = strAmIRight.ToString
End Sub
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.