Can some please advise me of what I'm doing wrong.
I'm new to visual basic 2012
What I am trying to do:
One input is saved into an Integer variable. The other input is saved into a Byte variable.
The output is calculated as the Integer * Byte/100 to the power 2.
If the user enters a non-numeric value, and clicks the button, show an error of "Illegal Value entered" using Messagebox.
If the user enters an "out of range" number, show an error of "input not in valid range" using Messagebox.
This is the code that I have:
Public Class Form1
Dim T1 As String
Dim T2 As String
Dim a As Integer
Dim b As Byte
Dim c As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
TextBox1.Text = False
TextBox2.Text = False
a = CInt(TextBox1.Text)
b = CByte(TextBox2.Text)
c = a * b / 100
c = c * a * b / 100 ^ 2
Label3.Text = "Output:" + c.ToString()
Catch ex As ArgumentOutOfRangeException
MessageBox.Show("Illegal Value Entered")
Catch ex As IndexOutOfRangeException
MessageBox.Show("Input not in valid range")
Catch ex As Exception
MessageBox.Show("Some exception has occured")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
Please remove the expressions TextBox1.Text = False (and for TextBox2) this would always force CInt() and CByte() to parse a string 'False' (not a user provided number). Your code should look like this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
a = CInt(TextBox1.Text)
b = CByte(TextBox2.Text)
c = a * b / 100
c = c * a * b / 100 ^ 2
Label3.Text = "Output:" + c.ToString()
Catch ex As ArgumentOutOfRangeException
MessageBox.Show("Illegal Value Entered")
Catch ex As IndexOutOfRangeException
MessageBox.Show("Input not in valid range")
Catch ex As Exception
MessageBox.Show("Some exception has occured")
End Try
End Sub
If you want to clear the numbers from textboxes after calculation, then please put these lines of code right after Label3.Text = ... line
TextBox1.Text = False
TextBox2.Text = False
CByte documentation clearly states that
If expression lies outside the acceptable range for the byte subtype,
an error occurs.
CByte(...) constructor would not be able to parse any number greater than 255.
Related
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
I'm working on a vb form, which allows a person to create an "account". I store the usernames and passwords in two arrays, and extract the information from them. But when I run the program, it comes up with a problem:
"An unhandled exception of type 'System.ArgumentNullException'
occurred in Microsoft.VisualBasic.dll, Additional information: Value
cannot be null."
where the code for the Button2/Register Button is (To be exact:
For i = 0 To (UBound(Usernames))
Could you help me out and tell me what to do differently/how to approach this situation? Here is the code:
Public Class Form1
Dim Usernames() As String
Dim Passwords() As String
Dim CurrName As String
Dim i As Integer
'Login button is pressed
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Index As Integer
CurrName = TextBox1.Text
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
Index = Array.IndexOf(Usernames, TextBox1.Text)
If TextBox2.Text = Passwords(Index) Then
Form3.Show()
Me.Hide()
End If
Else
MsgBox("The username or password is incorrect", MsgBoxStyle.Critical)
End If
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CurrName = TextBox1.Text
' *** Error (apparently) happens here ***
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
MsgBox("This username already exists!")
Else
ReDim Preserve Usernames(UBound(Usernames) + 1)
Usernames(UBound(Usernames)) = TextBox1.Text
ReDim Preserve Passwords(UBound(Passwords) + 1)
Passwords(UBound(Passwords)) = TextBox2.Text
End If
Next
End Sub
Private Function IfRepetition(ByRef Usernames() As String, CurrName As String, i As Integer) As Boolean
Dim j As Integer
'Checks for repetition of a username in the usernames array
IfRepetition = False
For j = 0 To (UBound(Usernames))
If Usernames(j) = CurrName Then
IfRepetition = True
Exit Function
End If
Next
End Function
End Class
The error you're getting is because UBound throws exception if the array is null.
Also using arrays for that isn't a good way, I recommend you use Dictionary for easier, shorter code.
Dim dic As New Dictionary(Of String, String) 'A new dictionary which handles usernames & passwords
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Login button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If Not dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it doesn't exist show error message and return ( don't continue )
MessageBox.Show("The username is incorrect")
Return
End If
If dic(TextBox1.Text) <> TextBox2.Text Then 'Validate entered username and password, if it's wrong show error message and return ( don't continue )
MessageBox.Show("The password is incorrect")
Return
End If
Form3.Show() 'If none of above error messages appear which means the entered username and password are correct, show Form3 and hide this form
Me.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'create account button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it exists show error message and return ( don't continue )
MessageBox.Show("This username already exists")
Return
End If
dic.Add(TextBox1.Text, TextBox2.Text) 'If none of above error messages which means it's okay to create this account, Add the username & password to the dictionary
End Sub
I am making a simple pricing calculator by using a Combobox and Label Text.
My Combobox has 2 items: Weekend (30.000) and Weekday (20.000). While the multiplier is quantity.
So if I choose "Weekend (30.000)" in the combobox and input "2" to qty, the result would be 30.000 * 2 = 60.000.
I tried this code but could not work.
I wonder how do I get the value of the strings from "Weekend (30.000)" to 30000?
Private Sub txtQty_TextChanged(sender As Object, e As EventArgs) Handles txtQty.TextChanged
Try
lblFinal.Text = cboPrice.SelectedItem * txtQty.Text
Catch ex As Exception
End Try
End Sub
Private Sub cboPrice_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPrice.SelectedIndexChanged
Try
If cboPrice.SelectedIndex = 1 Then
cboPrice.SelectedItem = "30000"
ElseIf cboPrice.SelectedIndex = 2 Then
cboPrice.SelectedText = "40000"
End If
Catch ex As Exception
End Try
End Sub
I tried again using this code and it worked. . .
Dim price as integer
Private Sub txtQty_TextChanged(sender As Object, e As EventArgs) Handles txtQty.TextChanged
Try
lblFinal.Text = Price * CInt(txtQty.Text)
Catch ex As Exception
End Try
End Sub
Private Sub cboPrice_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPrice.SelectedIndexChanged
Try
If cboPrice.SelectedIndex = 0 Then
Price = 30000
Else
Price = 40000
End If
Catch ex As Exception
End Try
End Sub
Hi I Just Want to Input 1 to 5 only as unit grades on textbox
i use this code:
Private Sub TextBox16_TextChanged(sender As Object, e As EventArgs) Handles TextBox16.TextChanged
If TextBox16.Text >= 5 Then
TextBox16.clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
End Sub
End Class
error came up:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Double' is not valid.
Alright you have two ways to do this:
Preventing Typing Them
In this case, you will deny user from typing other characters. So code this:
Private Sub TextBox16_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox16.KeyPress
'Deny user from entering more than one charecter
TextBox1.MaxLength = 1
Select Case e.KeyChar
Case "1", "2", "3", "4", "5" ,vbBack 'vbBack is backspace
'You can enter any number that you whant
e.Handled = False
Case Else
'Ignore the key
e.Handled = True
'Play a Beep sound.
Beep()
End Select
End Sub
or
Checking With TextChanged
Type in this in your method:
Dim textbox_val As Integer
'The user may enter alphabetical characters
Try
textbox_val = Convert.ToInt32(TextBox1.Text)
Catch ex As Exception
MsgBox("Unit Grades Only From 1 to 5")
Exit Sub
End Try
If textbox_val >= 5 Then
TextBox1.Clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
If you have your heart set on using a textbox for this , the following code should prevent any besides a 1 through 5 in the textbox. I used a textbox with a bit better naming txtUnitGrade.
Private _sLastValidValue As String = String.Empty
Private _bIgnoreChange As Boolean = False
Private Sub txtUnitGrade_TextChanged(sender As Object, e As EventArgs) Handles txtUnitGrade.TextChanged
If Not _bIgnoreChange Then
If txtUnitGrade.Text = String.Empty Then
_sLastValidValue = String.Empty
Else
If Not IsNumeric(txtUnitGrade.Text) Then
SetValueToLast()
Else
Dim iParsedValue As Integer = Integer.MinValue
If Not (Integer.TryParse(txtUnitGrade.Text, iParsedValue)) OrElse iParsedValue < 0 OrElse iParsedValue > 5 Then
SetValueToLast()
Else
_sLastValidValue = txtUnitGrade.Text
End If
End If
End If
End If
End Sub
Private Sub SetValueToLast()
Beep() 'you could add some other audible or visual cue that an block occured
_bIgnoreChange = True
txtUnitGrade.Text = _sLastValidValue
txtUnitGrade.SelectionStart = txtUnitGrade.Text.Length
_bIgnoreChange = False
End Sub
Hi all im getting a null reference run time error with one line of code in my project, however if i break point it and then step through it everything works fine. Any Thoughts
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim checkbox_l As String = "CheckBox"
Dim checkbox_i As string
For i As Integer = 1 To id Step 1
checkbox_i = checkbox_l + i.ToString
Try
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
My.Settings.name = Panel1.Controls("CheckBox" & i).Text
Call installer_properties()
Call start_install()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
The code is meant to check if a dynamically created checkbox has been checked and then move on accordingly, however im getting an error with the line
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
Use Debug.Assert to catch it
Dim c as Control = Panel1.Controls(checkbox_i)
Debug.Assert(c IsNot Nothing)
Dim cb as CheckBox = TryCast(c, CheckBox)
If cb isNot Nothing Then
If cb.Checked = True Then
My.Settings.name = cb.Text
Call installer_properties()
Call start_install()
End If
End If
To get result 1 if checked and 0 - if not, you can write down:
textbox1.text = Microsoft.VisualBasic.Right(Panel1.Controls("CheckBox" & i).ToString, 1)