Visual Basic Input Validation - vb.net

I am new to Visual Basic programming. I'm using a multi-line textbox to accept only numerical inputs from the users.
I need to remove any white space before adding it to my listbox. For example like ( 8) becomes 8 when added into the listbox and I shouldn't let the user proceed if there is no input or only whitespace as an input. Thank you in advance :)
For i As Integer = 0 To Val(TxtInput.Lines.Count) - 1
If TxtInput.Lines(i) = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(TxtInput.Lines(i)) Then 'Tests for Numbers
Temp.LbInput.Items.Add(TxtInput.Lines(i))
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next

This is the kind of thing linq-to-objects was made for:
Dim result = TxtInput.Lines.
Select(Function(line) line.Trim).
Where(Function(line) Not String.IsNullOrWhitespace(line) AndAlso IsNumeric(line)).
Select(Function(line) Val(line))
You can also do this:
Dim lines = TxtInput.Lines.Select(Function(line) line.Trim)
If lines.Any(Function(line) Not IsNumeric(line)) Then
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Exit Sub
Else
Dim result = lines.Where(Function(line) Not String.IsNullOrWhitespace(line)).
Select(Function(line) Val(line))
'Do more with "result" here
End If

Just store the trimmed line into a variable
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim() '<======================
If line = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(line) Then 'Tests for Numbers
Temp.LbInput.Items.Add(line)
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
Also, TxtInput.Lines.Count is an Integer already. No need to convert with Val, which, by the way, converts it into a Double.
Note that you can add items of any type to the ListBox, so you could as well convert the line into the desired type. I don't know if you need Integer or Double. Let's assume that you only want integer numbers. then you can change the code to
If TxtInput.Lines.Count = 0 Then
MsgBox("You have not entered anything. Please enter a number!", 1, "Error")
Else
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim()
Dim number As Integer
If line = "" Then
MsgBox("Your input is empty. Please enter some numbers!", 1, "Error")
ElseIf Integer.TryParse(line, number) Then 'Tests for Numbers
Temp.LbInput.Items.Add(number)
Temp.Show()
Else
MsgBox("Please enter only valid numbers!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
End If
(Code changed according to your comments.)
If you want doubles, just declare number as Double and convert with Double.TryParse(line, number).

Related

Validation to ensure value entered is a integer

I want a validation method that ensures that value entered is valid, it must be a integer (can include negative) and must not be blank. I have written this code, however not correct, can someone help me please. Thank you
If (b <> Integer Or " ") Then
Console.WriteLine("Value entered must be a number")
End If
new code:
Line98:
Console.WriteLine("Please input the value of, B:")
b = Console.ReadLine()
If Not Integer.TryParse(b, New Integer) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
so i used a select statement, and if a user enters "abckak" any non numerical data i get an error Unhandled Exception: System.InvalidCastException: Conversion from string "gakjdg" to type 'Integer' is not valid.
how could this be fixed, this is a quick example of my code
Console.WriteLine("..........Main Menu..........")
Console.WriteLine("Please input 1 ")
Console.WriteLine("Please input 2")
Console.WriteLine("Please input 3 ")
Console.WriteLine("Please input 4 ")
Console.WriteLine("Please input 5 for Help")
Console.WriteLine("Please input 6 to Exit")
Console.WriteLine("Please enter your choice: ")
Choice = Console.ReadLine()
Select Case Choice
case1; etc
Case Else
Console.WriteLine("Error: " & Choice & " is not a option, Please try again")
Look into Integer.TryParse, it will try and parse the string into a integer if it can, if it can't it wont throw an exception...
Dim b As Integer
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
If it can parse the input from the user, then b would be the value from the parse, otherwise the value of b is still 0...
Edit Per Comment
Dim b As Integer
Do Until b > 0
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) OrElse b <= 0 Then
Console.WriteLine("Value entered must be a number and not equal 0")
GoTo Line98
End If
Loop

Storing string then displaying it with a label box

I am trying to store the string from an input box and then display it with dashes in the lblbox for a hangman game for a class.
These are the tasks that I am struggling with:
edit the program to allow a Secret Word of any length.
the program will allow the ‘guesser’ to guess 2 times the length of the word. As an example, the word ‘code’ will allow 8 total guesses.
As the user guesses at letters contained in the word the program will:
Count the number of attempts the user has completed.
Replace the appropriate dash (-) with the correct letter, if the correct letter has been guessed.
When all the letters have been guessed correctly all the dashes (-) should be replaced with the appropriate letters, and a message box should appear stating “Great Job playing Hangman.!”
If the user is unable to guess the correct word in the amount of guesses allowed; the dashes (-) should be replaced with GAME OVER! and a message box should appear stating “Sorry the correct word was________”
2 bonus points will be awarded for displaying all incorrect letters guess in a 3rd label control.
4 more additional bonus points will be awarded for not allowing, or counting a user who guesses the same incorrect letter twice.
Here is my code:
Dim strSecretWord As String
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer = 10
Dim intNumofGuesses As Integer = 0
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = ""
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a 5 letter word for user to guess:", "Please input secret word.").ToUpper
'displays five dashes for the secret word
lblSecretWord.Text = lblSecretWord.Text & "-----"
'guessing player recieves inputbox to make letter guesses
MessageBox.Show("The length of the word is 5 letters, you will be given 10 guesses", "10 guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets (10) and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For intNumberofGuesses = 1 To 10
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To 4
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playign Hangman!", "Game Over", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
Else
End If
lblNumberOfAttempts.Text = intNumberofGuesses
intNumberOfRemainingGuesses = intNumberOfRemainingGuesses - 1
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
I added a list box to keep the guessed letters. Other comments and explanations in line.
Public Class Form3
'Move this to a class level variable so it can be seen by
'all the methods in the class
Private strSecretWord As String
Private Sub btnStartGame_Click(sender As Object, e As EventArgs) Handles btnStartGame.Click
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer
Dim intNumofGuesses As Integer = 0
'Display correct number of dashes
Dim numberOfDashes As Integer = strSecretWord.Length
'Create a string with correct number of dashes
'This uses and overload of the String constructor that takes a Char and an integer
'as arguments and returns a string with that character repeated that number
'of times. The lower case c following "-" indicates that - is a Char.
Dim TotalNumofGuesses = numberOfDashes * 2
lblRemainingNumberOfAttempts.Text = TotalNumofGuesses.ToString
intNumberOfRemainingGuesses = TotalNumofGuesses
Dim dashString As String = New String("-"c, numberOfDashes)
'displays the dashes
lblSecretWord.Text = dashString
'guessing player recieves inputbox to make letter guesses
'You can use an Interpolated string to display variables in line surrounded by { }.
'In older versions of VB String.Format() will yield the same result.
MessageBox.Show($"The length of the word is {numberOfDashes} letters, you will be given {TotalNumofGuesses} guesses", $"{TotalNumofGuesses} guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For counter = 1 To TotalNumofGuesses
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'If lstLettersGuessed.Contains(strLetterGuessed) Then
If lbxLettersGuessed.Items.Contains(strLetterGuessed) Then
MessageBox.Show($"{strLetterGuessed} has already been guessed.", "Try Again")
'need to do this so they are not cheated out of a guess
TotalNumofGuesses += 1
Continue For 'Moves to the next iteration of the For
End If
lbxLettersGuessed.Items.Add(strLetterGuessed)
'lstLettersGuessed.Add(strLetterGuessed)
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To numberOfDashes - 1
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playing Hangman!", "Game Over", MessageBoxButtons.OK)
'Do this at start of game, player wants to see final score
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
End If
'This is a shorter way of incrementing a variable
intNumofGuesses += 1
'Can't put an integer into a Text property, it needs a string
lblNumberOfAttempts.Text = intNumofGuesses.ToString
'This is a shorter way of decrementing a variable
intNumberOfRemainingGuesses -= 1
'Can't put an integer into a Text property, it needs a string
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses.ToString
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
'Do this at start of game
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
End Sub
Private Sub btnSetUp_Click(sender As Object, e As EventArgs) Handles btnSetUp.Click
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = "0"
lblRemainingNumberOfAttempts.Text = "0"
lbxLettersGuessed.Items.Clear()
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a word for user to guess:", "Please input secret word.").ToUpper
End Sub
End Class

How to allow alphanumeric text in datagridview but exclude negative numbers

I'm trying to allow only alphanumeric input in my datagridview column. Is there a way to allow alphanumeric input and also prevent the user from entering negative numbers or leaving the cell blank? If anyone has any suggestions or answers I would greatly appreciate it! :) Here is my code below. I already have the negative and blank cell validation working, but its not allowing me to input non-numeric input.
If (e.ColumnIndex = 0) Then 'checking value for column 1 only
Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then ' This will prevent any blank cells
MessageBox.Show("Name Cannot Be Empty")
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
ElseIf cellData < 0 Then
MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
Exit Sub ' Again this a default value I want supplied back to the datagridivewcell
End If
End If
So my code works, except when I enter any type of non-numeric character the program stops and exits.
Try using TryParse like this:
If (e.ColumnIndex = 0) Then 'checking value for column 1 only
Dim cellValue As Integer
If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellValue)) Then
If cellValue < 0 Then
MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
Exit Sub ' Again this a default value I want supplied back to the datagridivewcell
End If
Else
Dim testValue As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If (String.IsNullOrEmpty(testValue)) Then
MessageBox.Show("Name Cannot Be Empty")
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
End If
End If
End If

Input Validation for an integer in DataGridView

I'm able to use the code below to check whether or not a user inputs a string in a datagridview cell. If the user inputs a string a message pops up to tell them "only numeric entries are allowed". This is exactly what I want my code to do. However if I try to use this code in a column of data populated with numbers I get an error message that says "error happened, parsing commit". If anyone is able to figure out what the issue is here I would greatly appreciate it!
If (e.ColumnIndex = 3) Then 'checking numeric value for column 3 only
Dim value As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
For Each c As Char In value
If Not Char.IsDigit(c) Then
MessageBox.Show("Please Enter numeric Value")
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 3 'This will set the defaultvalue of the datagrid cell in question to the value of "3"
Exit Sub
End If
Next
End If
This solution not only checks for non-integer values it also works for every column populated with numbers for the entire datagridview. Also if the user inputs a non-integer if will supply a default value for the datagridviewcell, this default value is the previous number.
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
If StrComp(e.Exception.Message, "Input string was not in a correct format.") = 0 Then
MessageBox.Show("Please Enter a numeric Value")
'This will change the number back to original
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = " "
End If
End Sub
Do this in cellvalidating event ...
If (e.ColumnIndex = 3) Then 'checking numeric value for column 3 only
If Not Isnumeric(e.Formatted.Value) Then
MessageBox.Show("Please Enter numeric Value")
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 3 'This will set the defaultvalue of the datagrid cell in question to the value of "3"
Exit Sub
End If
End If

Console Application on VB2008 - Integer.TryParse Method Error

I am using Integer.TryParse Method to validate whether user input is a numeric or non-numeric in my program.
1)if the user input is numeric, the program will then proceed and validate that the user input is range from 0 to 9.
2)If the user is enter a non-numeric input, the program will display the message "invalid input" and ask user to start from beginning.
Following is my coding:
Sub Main()
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
Dim index As Integer
Dim number As Integer
Dim reEnter As Boolean = True
Console.WriteLine("Please enter 7 integers: ")
Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
Console.WriteLine()
While reEnter
For index = 0 To 6
Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.
If Integer.TryParse(sevenNumbers(index), number) Then
While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End While
Else
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End If
reEnter = False
Next
End While
End Sub
However, when a user enter a non-numeric input, the program can't continue and shows an error that forced to close.
i tried this
Sub Main()
Dim num As Integer
Console.Write("enter num:")
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
Console.WriteLine("valid. num = " & num)
Else
Console.WriteLine("invalid")
End If
End Sub
it does works and i am wondering which part of my coding is wrong??
Thank for help!!
Your two samples of code are different. In your second attempt, you do this:
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
The above code reads into a variable called input that will be a String (because Console.ReadLine returns a String). Then, you try to parse the string into a number.
However, in your original code, you do this (some lines omitted for clarity):
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
...
sevenNumbers(index) = Console.ReadLine()
In this case, you are reading into a variable that you have explicitly declared to be an Integer. If the user types "abc" then the conversion will fail at this point - you won't even get to the TryParse because you can't complete the innput.
Instead of reading to an integer, you need to read into a String variable and then parse that value into an Integer (as you did in your second code).
You could have spotted this yourself by taking note of the line that the error actually occurs on when debugging: you should note that the program crashes on the ReadLine, not on the TryParse.
Um. This line:
sevenNumbers(index) = Console.ReadLine()
Is storing whatever text has been read into an array of Integers. If it's compiling, then by the time you reach any later code, you're too late to control the conversion. It's already happened.
Maybe sevenNumbers should be String()?
(You really ought to turn on OPTION STRICT and OPTION EXPLICIT - it should find problems like this for you when it compiles the code)