Invalid input when integer is within valid means? - vb.net

I'm working on a VB program, rather basic (no pun intended), in which I need to convert basic integers to Roman numerals. I have the conversion part working perfectly with my Select Case. I also need to add validation input so if an invalid number is entered, the text box displays as such. Any number between 1 and 10 should result in the ability to click the convert button. Currently, any number I enter between 1 and 10 immediately displays, "That number is invalid."
This is my current code, which fails:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub lblRomanNum_Click(sender As Object, e As EventArgs)
End Sub
Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox1.TextChanged
Dim intNum As Integer
If intNum < 1 Or intNum > 10 Then
txtBox1.Text = "That number is invalid."
'ElseIf intNum > 10 Then
'txtBox1.Text = "That number is invalid"
End If
End Sub
Private Sub txtBox2_TextChanged(sender As Object, e As EventArgs) Handles txtBox2.TextChanged
End Sub
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
Select CInt(txtBox1.Text)
Case 1 ' numerical 1
txtBox2.Text = "I"
Case 2 ' numerical 2
txtBox2.Text = "II"
Case 3 ' numerical 3
txtBox2.Text = "III"
Case 4 ' numerical 4
txtBox2.Text = "IV"
Case 5 ' numerical 5
txtBox2.Text = "V"
Case 6 ' numerical 6
txtBox2.Text = "VI"
Case 7 ' numerical 7
txtBox2.Text = "VII"
Case 8 ' numerical 8
txtBox2.Text = "VIII"
Case 9 ' numerical 9
txtBox2.Text = "IX"
Case 10 ' numerical 10
txtBox2.Text = "X"
'Case Else
'If a user enters an invalid value, this message is displayed and no conversion is attempted, according to instructions.
'txtBox2.Text = "That value is invalid."
End Select
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub lblRomanNum_Click_1(sender As Object, e As EventArgs)
End Sub
End Class
Any intNum less than 1 should display the invalid message.
Any intNum greater than 10 should display the invalid message.
If I'm reading what I currently have correctly, this should work and allow me to enter a number between 1 and 10 without the invalid message appearing. Am I missing something here?

Try the brackets and the 'or'
1. Dim intNum As Integer
2. If (intNum < 1) or (intNum > 10) Then
3. txtBox1.Text = "That number is invalid."
4. End If

Your code perfectly worked for me in Visual Studio 2013 with .NET Framework 4.5.1. Try deleting entire block and re-type the code.
Or you can try this code as well
If intNum < 1 OrElse intNum > 10 Then
TextBox1.Text = "That number is invalid."
End If

Needed to add...
Integer.TryParse(txtBox1.Text, i)
...directly under my variable declaration.

Related

Click Button and Count Vb.Net

I want to Count how many times I click a button and display the number, but the format should be like: 0001 if reach 9999 restart to 0001 again and count till 9999.
I tried:
Private ButtonClickCount As Integer = 0
ButtonClickCount += 1
Label5.Text = "0000" & ButtonClickCount
And
Label5.Text = "0000" + Val(Label5.Text) + 1
This was the dumbest way I tried.lol
And the result was disapointing.
Is there any easy way to do it?
If you use a Static variable for the count, you can keep it in the button click event handler. (Static variables aren't used all that often, but it works here, assuming you don't need the variable anywhere else.)
If you check if the counter has reached 10000, you can set it back to 1.
You can format the number in the .ToString method.
Perhaps something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static clickCount As Integer = 0
clickCount += 1
If clickCount = 10000 Then
clickCount = 1
End If
lblClickCount.Text = clickCount.ToString("0000")
End Sub
You could use the Format command, which controls how many zeroes you want in the output:
Dim ButtonClicks As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ButtonClicks += 1
Label1.Text = Format(ButtonClicks, "0000")
End Sub
Dim ButtonClicks As Integer = 0
Private sub Button1_click(sender as object, e as EventArgs) handles Button 1.click
Buttonclick +=1
If buttonclick ="9999" then
Buttonlclick=1
Endif
Label1.text =format(Buttonclick, "0000")
End sub
You will need to keep track of the counter somewhere, in this case I would suggest storing the counter in the control's Tag property (documentation). In your button's click event, you would do the following:
Get the Tag
Convert the value to an Integer
Increment the value by 1
Check if the new value is greater than 9999
Optionally reset the value to 1 if 4 is true
Set the Text of the Button to the formatted result
Set the Tag of the button to the new value
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim clickedButton = DirectCast(sender, Button)
Dim tagValue = clickedButton.Tag
If (tagValue Is Nothing) Then
tagValue = 0
End If
Dim conversion As Integer
If (Not Integer.TryParse(tagValue.ToString(), conversion)) Then
conversion = 0
End If
conversion += 1
If (conversion > 9999) Then
conversion = 1
End If
clickedButton.Text = converstion.ToString("0000")
clickedButton.Tag = conversion
End Sub
Well, sorry guys, just realized that I could use the PadLeft function... And worked fine.
ButtonClickCount += 1
Label5.Text = ButtonClickCount.ToString().PadLeft(5, "0")
But Still don't know if it reaches 9999 will restart from 0001

how do I limit user's input in vb.net

Dim Number_of_courses As Integer
Number_of_courses = TextBox.Text
Number_of_courses > 0 and Number_of_courses < 8
I wish to limit the user's input from 1 to 8
Assuming WinForms...
Use Integer.TryParse to convert the STRING in your TextBox to an Integer. Then you can do the checks on it to make sure it's within range:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number_of_courses As Integer
If Integer.TryParse(TextBox1.Text, Number_of_courses) Then
If Number_of_courses > 0 And Number_of_courses < 8 Then
' ... do something with "Number_of_courses" in here ...
MessageBox.Show("Number_of_courses = " & Number_of_courses)
Else
MessageBox.Show("Invalid Number of Courses. Please enter a valid integer greater than zero and less then eight.")
End If
Else
MessageBox.Show("Invalid Number of Courses. Please enter a valid integer.")
End If
End Sub

How can I get ten numbers and displays the biggest and lowest one?

sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub

visual basic looping issue

I am a new programmer learning Visual Basic. Right now, I'm working on a project about a softball scoreboard. I have been working on this project for a bit, and I am confused on 1 thing.
The thing I am confused on is the proper place to place my loop. I am trying to do a while loop, but when I try it allows me to enter the 7 innings, but once I do it is an infinate loop with the message only seven innings are allowed and it does not display the lblTotal. It works without the loop, but it just doesnt allow me to enter all of the innings back to back. I would really appreciate if you could help me. I feel like I placed the loop in the wrong place.
Public Class frmSoftballScoreboard
Const VALID_MESSAGE As String = "Enter valid runs value"
Const ONLY_MESSAGE As String = "Only seven innings are allowed"
'Declaring array
Dim scores(6) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs : Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
Do While runs <= 7
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
Exit Sub
ElseIf runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
Loop
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
Private Sub mnuClear_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub mnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
Do While runs <= 7
'runs' variable should be updated (adding +1) within the 'Do While' loop in order to be able to satisfy the condition and break out.
(...)
runs += 1
Loop

Random Numbers to Text in Label

Public Class MainForm
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub guestsTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles guestsTextBox.KeyPress
' allows only numbers and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'fills the list box and selects the first item
typeListBox.Items.Add("Kid's Birthday")
typeListBox.Items.Add("21st Birthday")
typeListBox.Items.Add("40th Birthday")
typeListBox.Items.Add("Other Birthday")
typeListBox.SelectedIndex = 0
End Sub
Private Sub calcButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calcButton.Click
'displays the total charge
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Integer.TryParse(guestsTextBox.Text, guests)
typeIndex = typeListBox.SelectedIndex
'determine the price per guest
Select Case typeIndex
Case 0 'Kid's Birthday
guestPrice = 11
Case 1 '21st Birthday
guestPrice = 20
Case 2 '40th Birthday
guestPrice = 25
Case Else 'other birthdays
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
totalLabel.Text = totalCharge.ToString("C0")
End Sub
Private Sub testDataButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles testDataButton.Click
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Dim randomGen As New Random
Dim setCounter As Integer = 1
testDataLabel.Text = String.Empty
Do
guests = randomGen.Next(1, 51)
typeIndex = randomGen.Next(0, 4)
For Each I As Object In typeListBox.SelectedItems
testDataLabel.Text += I.ToString() & ControlChars.NewLine
Next
'determine the price per guest
Select Case typeListBox.SelectedIndex
Case 0
guestPrice = 11
Case 1
guestPrice = 20
Case 2
guestPrice = 25
Case Else
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
testDataLabel.Text = testDataLabel.Text &
typeIndex.ToString & " " &
guests.ToString & " " &
totalCharge.ToString("C0") &
ControlChars.NewLine
setCounter += 1
Loop Until setCounter > 10
End Sub
Private Sub typeListBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles typeListBox.SelectedIndexChanged
End Sub
End Class
When I click on a button named "Generate Test Data" It generates a list of random numbers in a label. I want these numbers to say the type of birthday instead of the number.
0 being "Kid's Birthday"
1 being "21st Birthday"
2 being "40th Birthday"
and 3 being "Other Birthday"
How would I go about doing this?
Any help would be much appreciated!
If I understood your question correctly, you can declare an enum and have a dictionary of that enum to String.
The Enum takes care of dealing with numbers in code, and rather use human readable constructs. Dictionary will make sure your users will also see human readable constructs.
Please see below code (needs a brand new WinForms project and a ListBox called ListBox1 on the main form):
Option Strict On
Public Class Form1
'Declare this enum to avoid dealing with naked numbers in code
Enum BirthdayTypes
btKids = 0
bt21st = 1
bt40th = 2
btOther = 3
End Enum
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
'Suppose your input value is a number,
'but you don't want to deal with numbers
Dim typeIndex As Integer = 2
'You can convert your number to BirthdayTypes,
'making your input "correct"
Dim typeIndexBt As BirthdayTypes = ConvertBirthdayIndexToType(typeIndex)
'Calculation of guest price is now "human readable"
Dim guestPrice As Integer = CalculateGuestPrice(typeIndexBt)
'You can create a dictionary for diplaying the values
Dim displayDictionary As New Dictionary(Of BirthdayTypes, String)
With displayDictionary
.Add(BirthdayTypes.btKids, "Kid's Birthday")
.Add(BirthdayTypes.bt21st, "21st Birthday")
.Add(BirthdayTypes.bt40th, "40th Birthday")
.Add(BirthdayTypes.btOther, "Other Birthday")
End With
'Here is how you would those values into a ListBox
With ListBox1
.DataSource = displayDictionary.ToList
.ValueMember = "Key"
.DisplayMember = "Value"
End With
'Now your ListBox displays strings,
'but SelectedValue would return an object of type BirthdayTypes
'You can extract random values from the above dictionary by index,
'and create a new list from it
Debug.WriteLine(ListBox1.SelectedValue) 'outputs btKids
End Sub
Private Function CalculateGuestPrice(bt As BirthdayTypes) As Integer
Select Case bt
Case BirthdayTypes.btKids : Return 11
Case BirthdayTypes.bt21st : Return 20
Case BirthdayTypes.bt40th : Return 25
Case BirthdayTypes.btOther : Return 15
End Select
'should never here
Throw New Exception("Unknown birthday type")
End Function
Private Function ConvertBirthdayIndexToType(index As Integer) As BirthdayTypes
If index < 3 Then Return CType(index, BirthdayTypes)
Return BirthdayTypes.btOther
End Function
End Class
Disclaimer: this code is just a demo of what can be done, not meant to be used a complete solution.
I would use a string.
Dim thestring() As String = {"Kid's Birthday", _
"21st Birthday", _
"40th Birthday", _
"Other Birthday"}
Now each of those numbers will represent the text in thestring.
thestring(0) = kids birthday
thestring(1) = 21 birthday
thestring(2) = 40th birthday
thestring(3) = other birthday
Make sense? I would help further, but i don't quite get what you are trying to do.