Warning if textbox is empty - vb.net-2010

I want a warning if textbox is empty when I click the button to do a math calculation.
Private Sub hitung_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles hitung.Click
Dim z, iterasi, n1, n2, n3 As Single
Dim fx0, fx1, fx2, x2, x0, x1 As Decimal
If a.Text = Nothing Or
b.Text = Nothing Or
g.Text = Nothing Or
h.Text = Nothing Or
i.Text = Nothing Or
j.Text = Nothing Then
MessageBox.Show("TextBox is empty", "No entry",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With a
.Focus()
.SelectAll()
End With
End If
x0 = (a.Text)
x1 = (b.Text)
n1 = (g.Text)
n2 = (h.Text)
n3 = (i.Text)
iterasi = (j.Text)
If I leave the textbox blank and press the button, I have an error
"Conversion from string "" to type 'Decimal' is not valid."
I changed the x0 to
x0 = Decimal.Parse(a.Text)
but the error says
"Input string was not in a correct format."

Nothing and an empty string are different things; You could use string.IsNullOrEmpty(a.Text) (etc.) in place of a.Text = Nothing for a more resilient approach

Here is the code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If a.Text = "" Then
MessageBox.Show("Empty TextBox", "No entry")
End If
End Sub
End Class

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

How to connect keyboard events to press down buttons in Visual Basic?

I'm making a hangman game as a project in school, and we can't make the keyboard to function with the buttons that we have in our game. We have 29 buttons with letters "A-Å" and we can only press them using the mousepad/mouse. I'm programming this in VisualBasic.
Public Class Form1
Private ord_liste() As String
Private ord As String
Private r As New Random
Private feil As Single
Private Sub btn_click(ByVal btn As Button)
btn.Enabled = False
Call check(btn.Text)
End Sub
Private Sub Buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click,
Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button15.Click, Button16.Click,
Button17.Click, Button18.Click, Button19.Click, Button20.Click, Button21.Click, Button22.Click, Button23.Click, Button24.Click, Button25.Click, Button26.Click,
Button27.Click, Button28.Click, Button29.Click
Dim btn As Button = DirectCast(sender, Button)
Call btn_click(btn)
End Sub
'This is whats not working for me...
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
For Each btn As Button In Panel1.Controls.OfType(Of Button)()
If e.KeyCode.ToString.ToLower = btn.Text.ToLower Then
Call btn_click(btn)
End If
Next
End Sub
Private Sub check(ByVal letter As String)
If ord.Contains(letter.ToLower) Then
'Sjekke om bokstaven passer i ordet.
Dim indexes As New List(Of Integer)
For i As Integer = 0 To ord.Length - 1
If ord.Substring(i, 1).ToLower = letter.ToLower Then
indexes.Add(i)
End If
Next
'Denne gjør at når du gjetter rett bokstav så blir den skrevet ut i tekstboksen.
For Each Int As Integer In indexes
TextBox1.Text = TextBox1.Text.Remove(Int * 4, 4).Insert(Int * 4, letter.ToUpper & " ")
Next
'Du har vunnet
If TextBox1.Text.Contains("_") = False Then
MessageBox.Show("Gratulerer, du har vunnet!", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
Call nyttspill()
End If
Else
'Du gjettet feil bokstav.
feil += 1
Select Case feil
Case 1
Head.Visible = True
Case 2
Body.Visible = True
Case 3
Left_arm.Visible = True
Case 4
Right_arm.Visible = True
Case 5
Left_leg.Visible = True
Case 6
Right_leg.Visible = True
MessageBox.Show("Beklager, men du har tapt. Ordet du skulle ha var: " & ord, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
Call nyttspill()
End Select
End If
End Sub
Private Sub nyttspill()
'Starter spillet på nytt og gjemmer kroppen.
Head.Visible = False
Body.Visible = False
Left_arm.Visible = False
Right_arm.Visible = False
Left_leg.Visible = False
Right_leg.Visible = False
'Setter antall feil til 0.
feil = 0
'Velger nytt random ord.
Dim i As Integer = r.Next(0, ord_liste.Count)
ord = ord_liste(i)
'Viser hvor langt det er.
TextBox1.Clear()
For int As Integer = 0 To ord.Length - 1
TextBox1.Text &= "__ "
Next
'Knappene blir "utrykket" igjen.
For Each btn As Button In Panel1.Controls.OfType(Of Button)()
btn.Enabled = True
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim del() As String = {Environment.NewLine}
ord_liste = My.Resources.ord_fil.Split(del, StringSplitOptions.RemoveEmptyEntries)
Call nyttspill()
End Sub
End Class
This is the code we have so far.
Borrowing the technique from this question, in your KeyDown handler you'll need to:
Identify which key/letter was pressed (a Case statement, perhaps)
Change the appropriate button's FlatStyle property,
cmdAbutton.FlatStyle = FlatStyle.Flat
Call the event handler for the appropriate button, or perform the desired code,
cmdAbutton.PerformClick()
Then, create a KeyUp handler very similar to your KeyDown where you,
Identify which key/letter was pressed, and
Revert the appropriate button's FlatStyle,
cmdAbutton.FlatStyle = FlatStyle.Standard

Navigating through datagridview cells with enter key

I've tried several combinations but didn't have any success. When button is pressed focus is on yellow (1), I would like when enter key is pressed, that focus goes to cell (2), then (3) and so on.
If there are no cell edits, with just enter key everything is fine with this code :
Private Sub DGVBU1_KeyDown(sender As Object, e As KeyEventArgs) Handles DGVBU1.KeyDown
If e.KeyCode = Keys.Enter Then
Dim CLIndex As Integer = DGVBU1.CurrentCell.ColumnIndex
Dim RWIndex As Integer = DGVBU1.CurrentCell.RowIndex
If CLIndex = 2 Then
DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex - 1).Cells(CLIndex + 1)
ElseIf CLIndex = 3 Then
DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
End If
End If
End Sub
But when Enter key is pressed after cell edit it goes down to row+1.
I've also tried this :
Private Sub DGVBU1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DGVBU1.CellEndEdit
Dim CLIndex As Integer = DGVBU1.CurrentCell.ColumnIndex
Dim RWIndex As Integer = DGVBU1.CurrentCell.RowIndex
If CLIndex = 2 Then
DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
DGVBU1.CurrentCell = DGVBU1.Rows(8).Cells(CLIndex + 1)
ElseIf CLIndex = 3 Then
DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
End If
End Sub
...but then enter key send focus from (1) directly to cell (4).
Is it possible to make this work?
Thanks for any help.
If the DataGridView may be intercepting the Enter key in the keydown event. If this is the problem, a solution is to derive the control class and override ProcessCmdKey:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keydata As Keys) As Boolean
If keydata = Keys.Enter Then
OnKeyDown(New KeyEventArgs(keydata))
ProcessCmdKey = True
Else
ProcessCmdKey = MyBase.ProcessCmdKey(msg, keydata)
End If
End Function
Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.Enter Then
Select Case DataGridView1.CurrentCell.ColumnIndex
Case 0
e.Handled = True
DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(DataGridView1.CurrentCell.ColumnIndex + 1).Selected = True
Case 1
e.Handled = True
Try
DataGridView1.Rows(DataGridView1.CurrentRow.Index + 1).Cells(2).Selected = True
Catch ex As Exception
End Try
End Select
End If
End Sub

I'm doing a VB.net Caesar Cipher

Good day,
i'm having trouble of finishing this homework :<
i'm doing a caesar cipher where the user will have a txt file
then the program will find the text file and read what's inside of it
then overwrite the text file
so far i'm able to do the code but i'm getting a
index out of range and nullreference exception
here's my code
Imports System.IO
Public Class main_form
Dim x, y, z, str_len As Integer 'where x is a counter for the array
Dim loc, read(5), write(), str_1, str_2, aa As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub brw_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles brw_btn.Click
TextBox1.Clear()
OFD1.ShowDialog()
TextBox1.Text = OFD1.FileName
loc = OFD1.FileName
read = File.ReadAllLines(OFD1.FileName)
End Sub
Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
'Formula of Caesar's Cipher
z = 1
x = 0
If read(x) <> "" Then
While read(x) <> ""
str_2 = ""
str_1 = read(x)
str_len = Len(str_1)
MessageBox.Show(str_2)
For i As Integer = 0 To str_len - 1
y = Asc(Mid(str_1, i + 1, i + 2))
y = y + Val(TextBox2.Text)
str_2 = str_2 + Chr(y)
MessageBox.Show(str_2)
Next
MessageBox.Show(str_2)
write(x) = str_2
File.AppendAllLines(OFD1.FileName, write(x))
x += 1
End While
Else
End If
End Sub
End Class
Thanks!
Of course you are getting out of range exception because :
While read(x) <> ""
...
...
x += 1 'if x goes out of range the next loop in while will access read(x <-out of range)
End While
You have to insert
While read(x) <> ""
...
...
x += 1
If x >= read.Length
Exit While
End If
End While
Also:
Dim write() as String
...
write(x) = str_2 '<-write is used un initialized, null reference exception
Change write() to write or:
Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
ReDim write(read.Length) '<---
z = 1
x = 0
If read(x) <> "" Then
...
...
Valter

Visual Basic - Calculator II coding dilemmas

Here is an assignment I was issued in Computer Science I [Visual Basic 2010]
Objective:
Modify the CalculatorII case study to display "ERROR" if a division by 0 is attempted. "ERROR should also be displayed if more than one decimal points are entered for a single number.
I can't get the ERROR message to show up when I divide by zero or add more decimal points. Here's what I have in coding:
Public Class Form1
Dim operand1 As Double = 0
Dim operand2 As Double = 0
Dim op As String = Nothing
Dim newOperand As Boolean = True
Private Sub Number_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
btnDot.Click, btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, _
btn6.Click, btn7.Click, btn8.Click, btn9.Click
Dim btnNumberClicked As Button = sender
If newOperand Then
Me.txtDisplay.Text = btnNumberClicked.Tag
newOperand = False
Else
Me.txtDisplay.Text &= btnNumberClicked.Tag
End If
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnClear.Click
Me.txtDisplay.Text = "0"
operand1 = 0
operand2 = 0
newOperand = True
op = Nothing
End Sub
Private Sub btnOff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
btnOff.Click
Application.Exit()
End Sub
Private Sub btnOperator_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnPlus.Click, btnMinus.Click, btnTimes.Click, btnDivide.Click, btnEqual.Click, btnIntDivide.Click
Dim operatorSelected As Button = sender
If (operand1 = 0 And op = Nothing) Or op = "=" Then
operand1 = Val(Me.txtDisplay.Text)
ElseIf (operand1 = 0 And op = "/") Then
MessageBox.Show("ERROR")
Else
operand2 = Val(Me.txtDisplay.Text)
operand1 = Calculate(operand1, operand2, op)
Me.txtDisplay.Text = operand1
End If
op = operatorSelected.Tag
newOperand = True
End Sub
Function Calculate(ByVal firstOperand As Double, ByVal secondOperand As Double, _
ByVal op As String) As Double
Select Case op
Case "+"
Return (firstOperand + secondOperand)
Case "-"
Return (firstOperand - secondOperand)
Case "X"
Return (firstOperand * secondOperand)
Case "/"
Return (firstOperand / secondOperand)
Case "\"
End Select
End Function
End Classenter code here
Operand 2 has to be the error-field, you just check if the first operand is 0
change
"ElseIf (operand1 = 0 And op = "/") Then
to ElseIf (operand2 = 0 And op = "/") Then
Give it a try :)