How to compare textbox value to txt file - vb.net

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim linenumber0 As Integer
linenumber0 = 0
Dim mass As Double
mass = (File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
If (Math.Abs((cDbl(TextBox1.Text) - mass < 0.5) Then
TextBox1.BackColor = Color.Green
End If
Im getting an error conversing from string to double is not valid. It is probably a simple solution but i cant see it right now

Your error occurs because the data read from the file is a String, however you are attempting to assign it to a variable declared as Double.
You can use TryParse to convert the String to Double, avoid errors and provide appropriate feedback.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lineNumber0 As Integer
Dim mass As Double
Dim input As Double
If Double.TryParse(File.ReadAllLines("225.txt").ElementAt(linenumber0), mass) Then
If Double.TryParse(TextBox1.Text, input) AndAlso Math.Abs(input - mass) < 0.5 Then
TextBox1.BackColor = Color.Green
End If
Else
'Bad file input
End If
'...
End Sub

I think that when you set the value to mass is catching a String, so parse it with a simple CDbl, like this
mass = cDbl(File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
I supose that with this fix it will works.
Just in case, surround it with a TRY CATCH in case what it reads is not valid

Related

VB Entering a Non_Numeric value crashes the program

Please consider adding a description to this question to attract more helpful responses.
Public Class Form1
Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
Dim intvalue As Integer = CInt(TxtInputClassA.Text)
Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
Dim total As Double
Try
LblStatus.Text = String.Empty
LblClassAResult.Text = (intvalue * 15).ToString("c")
LblClassBResult.Text = (intvalue2 * 12).ToString("c")
LblClassCResult.Text = (intvalue3 * 9).ToString("c")
total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
LblTotal.Text = total.ToString("c")
Catch
LblStatus.Text = "Please Enter a Number"
End Try
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
Me.Close()
End Sub
Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
TxtInputClassA.Clear()
TxtInputClassB.Clear()
TxtinputClassC.Clear()
LblClassAResult.Text = String.Empty
LblClassBResult.Text = String.Empty
LblClassCResult.Text = String.Empty
LblTotal.Text = String.Empty
End Sub
End Class
VB Entering a Non_Numeric value crashes the program
Validation is built right into Windows Forms so you should make use of it. If you want to force the user to enter numbers in each of three TextBoxes then you can do this:
Private Sub TextBoxes_Validating(sender As Object, e As ComponentModel.CancelEventArgs) Handles TextBox3.Validating, TextBox2.Validating, TextBox1.Validating
Dim tb = DirectCast(sender, TextBox)
If Not Integer.TryParse(tb.Text, Nothing) Then
'Select all the invalid text and highlight it.
tb.SelectAll()
tb.HideSelection = False
MessageBox.Show("Please enter a whole number",
"Invalid Input",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
'Remove highlight when TextBox is not focused.
tb.HideSelection = True
'Don't let the control lose focus while data is invalid.
e.Cancel = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'All data is valid so proceed.
Dim n1 = CInt(TextBox1.Text)
Dim n2 = CInt(TextBox2.Text)
Dim n3 = CInt(TextBox3.Text)
'...
End If
End Sub
The ValidateChildren method will raise the Validating event for every control on the form and return False if any fail validation, i.e. e.Cancel is set to True in any event handlers, so that ensures that even controls that never received focus will be validated before the data is used.
Its bombing out on your cast "CInt(*value*)" so you can fix the code a couple ways. You can move your try above the casts like...
Try
Dim intvalue As Integer = CInt(TxtInputClassA.Text)
Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
Dim total As Double
LblStatus.Text = String.Empty
You can do a data validation on your inputs and exit if they aren't all numeric (put this above your Dim intvalue code)
For Each value As String In {TxtInputClassA.Text, TxtInputClassA.Text, TxtInputClassA.Text}
If Not IsNumeric(TxtInputClassA.Text) Then
LblStatus.Text = "Please Enter a Number"
Exit Sub
End If
Next
Instead of casting as an int, use the tryparse method on Int32...
Dim intvalue As Integer
If Not Int32.TryParse(TxtInputClassA.Text, intvalue) Then
Exit Sub
End If
Or you could intercept the keypresses on each text box so that only numbers can be entered
Private Sub TxtInputClassA_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
e.Handled = True
End If
End Sub
You can make that routine universal and append the event handler for all three text boxes like...
Private Sub EnforceOnlyNumericKeyPresses(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress, TxtInputClassB.KeyPress, TxtInputClassC.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
e.Handled = True
End If
End Sub
Choose your favorite or do all of them, lots of choices.
Replace your textboxes with NumericUpDown controls and retrieve their .Value for your calculation. NUDs don't allow non numeric input and can have a fixed number of decimal places which may also be useful in a financial context

Random Band Name Generator

I'm trying to make a random band name generator in vb.net but whenever i randomly generate it shows a number rather than a word from my combo boxes
Public Class Form1
Private Sub btnMake_Click(sender As Object, e As EventArgs) Handles btnMake.Click
Randomize()
ComboBox1.Text = Int(Rnd() * ComboBox1.Items.Count)
ComboBox2.Text = Int(Rnd() * ComboBox2.Items.Count)
txtResult.Text = ComboBox1.Text + " " + ComboBox2.Text
End Sub
Private Sub btnFavourite_Click(sender As Object, e As EventArgs) Handles btnFavourite.Click
ListBox1.Items.Add(txtResult.Text)
End Sub
End Class
it should print one of the names that I've put into the combo box at random but it gives me random numbers instead
Set the SelectedIndex property instead of Text
ComboBox1.SelectedIndex = Int(Rnd() * ComboBox1.Items.Count)
Put Option Strict On at the top of your code file. You will see the compile error
Option Strict On disallows implicit conversions from 'Single' to 'String'.
on this line
ComboBox1.Text = Int(Rnd() * ComboBox1.Items.Count)
because Int() returns the integer portion of a number in the same type it was passed. So pass it a single, and it returns a single.
From Microsoft.VisualBasic metadata:
' Summary:
' Return the integer portion of a number.
' ...
Public Function Int(Number As Single) As Single
But you don't want to set the ComboBox.Text equal to a number anyway. You may want to set the ComboBox.SelectedIndex. You can try
ComboBox1.SelectedIndex = Int(Rnd() * ComboBox1.Items.Count)
but with Option Strict On, you still have type mismatch because you're trying to set an integer to a single. You could wrap Int in a CInt conversion
ComboBox1.SelectedIndex = CInt(Int(Rnd() * ComboBox1.Items.Count))
but now it's getting out of hand...
Here's the issue: you're using outdated functions, Int and Rnd. These were brought over from VB6 days and if you use VB.NET functions, it's a whole lot easier. See the Random class. Using Random, you have access to Random.Next, which actually returns an integer. Great!
Dim r As New Random()
ComboBox1.SelectedIndex = r.Next(ComboBox1.Items.Count)
ComboBox2.SelectedIndex = r.Next(ComboBox2.Items.Count)
Here is the complete code (with an added event handler to update txtResult whenever the indices are changed i.e. when the user manually changes one)
Private Sub btnMake_Click(sender As Object, e As EventArgs) Handles btnMake.Click
Dim r As New Random()
ComboBox1.SelectedIndex = r.Next(ComboBox1.Items.Count)
ComboBox2.SelectedIndex = r.Next(ComboBox2.Items.Count)
End Sub
Private Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox2.SelectedIndexChanged
txtResult.Text = ComboBox1.Text & " " & ComboBox2.Text
End Sub
Private Sub btnFavourite_Click(sender As Object, e As EventArgs) Handles btnFavourite.Click
ListBox1.Items.Add(txtResult.Text)
End Sub

Convert each String in ListBox1 to Integer and add to ListBox2: Incorrectly formatted input string

I have one TextBox, two ListBoxes and two Buttons. The first Button separates each String in the TextBox and adds them one by one to ListBox1. The second Button converts each String in to an Integer. But I get an exception thrown by the debugger:
Incorrectly formatted input string.
System.FormatException was unhandled
HResult=-2146233033
Message=Cadeia de caracteres de entrada com formato incorrecto.
Source=mscorlib
StackTrace:
em System.Number.StringToNumber(String str, NumberStyles options,
NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
em System.Number.ParseDecimal(String value, NumberStyles options,
NumberFormatInfo numfmt)
em System.Convert.ToDecimal(String value)
em g_.Form2.Button2_Click(Object sender, EventArgs e) em
C:\Users\Utilizador\Documents\Visual Studio
2012\Projects\g+\g+\Form2.vb:line 17
I have inserted code to clean the empty spaces but it continues to throw the same error.
After to reflecting to the problem i have decide to change the way to do it
This is my code:
Public Class Form2
Dim frequency
Dim interval
Dim textconverted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myArray() As Char
myArray = Me.TextBox1.Text.ToCharArray
For Each chr As Char In Me.TextBox1.Text
ListBox1.Items.Add(chr)
Next
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If ListBox1.GetItemText(ListBox1.Items(i)) = String.Empty Then
ListBox1.Items.RemoveAt(i)
End If
Next i
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For i As Integer = 0 To ListBox1.Items.Count - 1
If (ListBox1.Items(i).ToString.Contains("a")) Then
ListBox2.Items.Add("1") 'Indexing is zero-based
Exit For
End If
Next
End Sub
End Class
Well i find a different way to do it and its do what i need.
This is the working solution
Public Class Form2
Dim frequency
Dim interval
Dim textconverted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myArray() As Char
myArray = Me.TextBox1.Text.ToCharArray
For Each chr As Char In Me.TextBox1.Text
ListBox1.Items.Add(chr)
Next
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If ListBox1.GetItemText(ListBox1.Items(i)) = String.Empty Then
ListBox1.Items.RemoveAt(i)
End If
Next i
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myVariable As String = "foo"
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.Items(x) = "a" Then
ListBox2.Items.Add("1")
End If
If ListBox1.Items(x) = "b" Then
ListBox2.Items.Add("2")
End If
If ListBox1.Items(x) = "c" Then
ListBox2.Items.Add("3")
End If
Next
End Sub
End Class
But now i have other problem with it it only check one string
How can i verify multiple strings there?
I added .ToString to your button 2 code and it worked fine. Turn on Option Strict; you will avoid some runtime errors. I have posted code that will handle a-z instead of a bunch of if statements. Add .ToLower to your TextBox1.Text.ToLower myArray is never used neither is myVariable.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For x As Integer = 0 To ListBox3.Items.Count - 1
Dim s As String = (Asc(ListBox3.Items(x).ToString) - 96).ToString
ListBox2.Items.Add(s)
Next
End Sub

How to "add" not "overwrite" amount using WriteDMAInteger

I'm making a program that changes address values however I want to be able to "add" lets say "500" to the current address. Not to change "1500" to "500". Any ways I can make this happen?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ammount As String = TextBox1.Text
Try
WriteDMAInteger("Process.dat", GetModuleHandle("Process.dat", "Process.dat") + &H3B80F8, {&H790}, ammount, 1, 4)
Catch ex As Exception
End Try
End Sub
Big thanks to #Visual Vincent for recommending or reminding me to use the "ReadDMAInteger" method. Using "ReadDMAInteger" I'm able to read the value of a address and have that be the value of the integer. From there I can simply use the integer and plug and play.
Of course, you would want to have a timer setup using this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
My.Computer.Audio.Play(My.Resources.Speech_Sleep, AudioPlayMode.Background)
Dim ammount As String = TextBox1.Text
Dim total1 As Integer
Dim totalstring1 As Integer
Dim final1 As Integer
total1 = ReadDMAInteger("Process.dat", GetModuleHandle("Process.dat", "Process.dat") + &H3B80F8, {&H790}, 1)
totalstring1 = TextBox1.Text.Trim
final1 = (total1 + totalstring1)
Try
WriteDMAInteger("Process", GetModuleHandle("Process.dat", "Process.dat") + &H3B80F8, {&H790}, final1, 1, 4)
Catch ex As Exception
End Try
End If

VB.net invalid length for a base 64 char array or string

I have an issue with conversion from a base-64 string to normal, readable text. I did some research and found that base 64 strings have to be of a length that is a multiple of 4. So I used padRight to give it a valid length, but I keep getting the same error. For example, I enter "hi" and it encodes as "⚫aGk====", which seems like 8 characters to me (which is obviously a multiple of 4). When I try to read it, it reads in with a length of 1.
I'm also using a custom file extension that I just called ".bgs". I'm not sure if that does anything. Writing to this file as a base64 string and reading/decoding it is the only thing I'm trying to do.
Here is my code:
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using bs As New BinaryWriter(File.Open("saveFile.bgs", FileMode.Create))
Dim originText As String = TextBox1.Text
Dim cipherText As String
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(originText)
cipherText = Convert.ToBase64String(byteArray)
Dim realLength As Integer = cipherText.Length() + 1
Dim len As Integer = (realLength Mod 4)
If (len > 0) Then bs.Write(cipherText.PadRight(realLength + (3 - len), "="))
bs.Close()
End Using
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Using bs As New BinaryReader(File.Open("saveFile.bgs", FileMode.Open))
Dim cipherText2 As String = bs.Read()
Dim originText2 As String = "Failed"
TextBox2.Text = cipherText2.Length() 'reports length of 1
Try
Dim byteArray2 As Byte() = Convert.FromBase64String(cipherText2)
originText2 = System.Text.Encoding.UTF8.GetString(byteArray2)
Catch ex As Exception
End Try
'TextBox2.Text = originText2
End Using
End Sub
Any help is much appreciated!
Update: it looks like the first character (the dot in the case above) seen in the .bgs file when I open it with notepad controls the contents of cipherText2, which is just a number, explaining why the length is so low.
Base64 encodes using only printable ASCII characters.
You are seeing the dot because you are using binary writer which prefixes strings with their length when writing to file.
Then you are using Read instead of ReadString so you read the string length as a number (which is then implicitly converted to string because you are not using Option Strict On like you should).
You can fix it by using ReadString instead of Read, but it would be easier if you used a text writer.
You also should not try to pad results of ToBase64String. It already gives you the correct string.
I would rewrite your code as:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim originText As String = TextBox1.Text
Dim cipherText As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(originText))
System.IO.File.WriteAllText("saveFile.bgs", cipherText, System.Text.Encoding.ASCII)
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim cipherText2 As String = System.IO.File.ReadAllText("saveFile.bgs", System.Text.Encoding.ASCII)
Dim originText2 As String = "Failed"
originText2 = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(cipherText2))
'TextBox2.Text = originText2
End Sub