Check if textbox contains specific decimal numbers - vb.net

I'm doing a school project but we weren't really taught about complex parts like this, so I'm hoping someone can help me.
I want my program to check whether my textbox contains 0.1-0.4 decimal numbers when I click a button. If yes, a message box will show that 0.5 or any half number must be entered. But, if the textbox contains 0.6-0.9, the message box will say to enter a whole number.
I know the message box part, I just don't know how to check those specific decimal numbers in the textbox. And also, if the textbox contain a whole number or a half number (.5), it will proceed to do what is stated.
If (Textbox1=0.1-0.4) Then
MsgBox("Enter a half number.")
ElseIf (TextBox1=0.6-0.9) Then
MsgBox("Enter a whole number.")
ElseIf (TextBox1=Half Number or TextBox1=Whole Number) Then
MsgBox("Transaction complete.")
End If

You can use a Select statement once you have converted the TextBox's Text to a numeric value:
Sub CheckDecimals(number As String)
If IsNumeric(number) Then
' Convert number to Single
Dim singleNumber As Single = CSng(number)
' Use Mod to get fraction only
Dim modNumber As Single = singleNumber Mod 1
Select Case modNumber
Case 0, 0.5
MsgBox("Transaction complete.")
Case Is < 0.5
MsgBox("Enter a half number.")
Case Is > 0.5
MsgBox("Enter a whole number.")
End Select
Else
MsgBox("Please enter a number.")
End If
End Sub
In your button Click event handler, use:
CheckDecimals(TextBox1.Text)

Related

(VB.Net) Prevent Duplicates from being added to a list box

I'm having some trouble with catching duplicates in an assignment I'm working on.
The assignment is a track and field race manager. Times are read from a text file, a bib number is then entered for each time loaded from the text file (aka, however many rows there are in the time text file)
The bib numbers and times are then synced in the order from which they were entered. A requirement is that the Bib numbers must be entered one at a time using an input box. Every time a bib number is entered, it is loaded to a list box called lstBibs.
The Issue
I have limited experience working with input boxes, and any attempts Ive made so far to check for duplicates has been ignored in Runtime. I'm also unsure where I would put a loop that checks for duplicates in the input box. Below is my code so far.
Dim i As Integer = 0
Dim Bibno As Integer = 0
Dim strrow As String = ""
Dim count As Integer = 0
Dim errorCount1 As Integer = 0
'Reads through the number of rows in the Time Text File.
'The Number of rows we have in the text file corresponds to the number
'of bib numbers we need. Thus the input box will loop through bib
'numbers until
'we reach the amount of loaded times
Try
For Each item In lstTimeEntry.Items
i += 1
For Bibno = 1 To i
count += 1
Bibno = InputBox("Enter Bib #" & count)
lstBibs.Items.Add(count & " - " & Bibno)
btnSyncTimesBibs.Enabled = True
Next
Next
Catch ex As Exception
'Catches any invalid data that isnt a number
MsgBox("Invalid Input, Please Try Again", , "Error")
lstBibs.Items.Clear()
btnSyncTimesBibs.Enabled = False
End Try
So I'm assuming that I must use a for loop that checks each list box item for a duplicate, I'm just unsure where this loop would go in relation to the code above.
Any and all help is very much appreciated. Thank you.
Don't use exception handling for something that isn't exceptional. Exceptionsl things are things beyond our control like a network connection that isn't available. A user failing to enter proper input is not at all exceptional. Validate the input. Don't make the user start all over again by clearing the list, just ask him to re-enter the last input.
I validate the user input with a TryParse. If the first condition succeeds then the AndAlso condition is checked. It the TryParse fails then the AndAlso condition is never evaluated so we will not get an exception. The second condition is checking if the number has already been used. Only if both conditions pass do we add the number to the used numbers list, update the lstBibs and increment the count.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Bibno As Integer
Dim count As Integer = 1
Dim usedNumbers As New List(Of Integer)
Do While count <= lstTimeEntry.Items.Count
Dim input = InputBox("Enter Bib #" & count)
If Integer.TryParse(input, Bibno) AndAlso Not usedNumbers.Contains(Bibno) Then
usedNumbers.Add(Bibno)
lstBibs.Items.Add(count & " - " & Bibno)
count += 1
Else
MessageBox.Show("Please enter a number that does not appear in the list box")
End If
Loop
End Sub
As per Steven B suggestion in the comments, you can check it like this:
If Not listTimeEntry.Items.Contains(itemToBeInserted) Then
listTimeEntry.Items.Add(itemToBeInserted)
End If

Forcing user to enter one entry from two options not to write it together

i have two text boxes : percentage and txtamount
i want to force user to enter percentage or amount not to write it together
casue if he did entered % and amount it makes some problems with me as i have alot of formulas
thanks
What I have tried:
privite sub post_click()
If (Me.percentage.Value >= 0 And Me.txtamount.Value >= 0) Then MsgBox " You should select % or amount ": Exit Sub
If you want to ensure that one (and only one) of your two textboxes has a value in it, use the following:
Private Sub post_Click()
If Not (Me.percentage.Value = "" Xor Me.txtamount.Value = "") Then MsgBox "You should select % or amount": Exit Sub
Testing for >= 0 won't work if the textbox is empty (because "" >= 0 will give a type mismatch). Testing for whether the textbox is "" will give a better indication of whether data has been entered.
Using Xor (which returns True iff one operand is True and the other is False) will therefore determine whether only one textbox has been filled in and the other left empty, and the Not will display the message if that is not the case.

Textbox value summation

I have two textboxes in which users enter a number, Data1.text and Data2.text. I need to do a simple check before proceeding and closing a form, i.e. the process should check if the sum of the values in Data1 and Data2 textbox is greater or lesser than the value from a label text named FinalValue.text, which gets its value from my main form.
If Data1.Text + Data2.Text <> FinalValue.Text Then
MessageBox.Show("The sum of the entered values are different from the final value!")
Exit Sub
End If
The problem is that whatever the user enters in the two textboxes, the messagebox pops up.
For example...if the FinalValue label has a value of 58.50, and if the user enters in one textbox 50 and in the other one 8.50, the messagebox pops up. I suppose I have to format my textboxes or something like that, but not sure in which way.
Thanks,
When you do Data1.Text + Data2.Text, you are actually just concatenating the values, not doing a number Sum, you need to convert to decimal.
Something like :
If Decimal.Parse(Data1.Text) + Decimal.Parse(Data2.Text) <> Decimal.Parse(FinalValue.Text) Then
MessageBox.Show("The sum of the entered values are different from the final value!")
Exit Sub
End If
Assuming the values are integers , change your condition to match the integers sum, You are currently concatenating the strings
CInt(Data1.Text) + CInt(Data2.Text) <> CInt(FinalValue.Text)
Or for Decimals use Decimal.Parse() in place of CInt()

Do Until Loop InputBox infinitely loops

I am creating a probability macro where user enters number of players in a card game. If I enter string (ex, Joe), non-integer(ex, 15.67), or integer less than 0 (ex, -25), the InputBox should loop. However, integers greater than 0 should terminate the loop. (I have to force kill Excel to stop the InputBox regardless of user input.)
I want the InputBox to close / Exit Sub once an integer greater than 0 is entered. What am I doing wrong here?
Sub GenerateCards()
Players = InputBox("How many players? Please enter an integer.")
Do Until TypeName(Players) = "Integer" And Players > 0 ' why does this loop even if both conditions are met (ex, Players=5?)
Players = InputBox("How many players? Please enter an integer.")
Loop
End Sub
InputBox() always returns a string, so TypeName() will always return "String".
But you can test if the string that's returned is an integer. First, you can use IsNumeric() to test if the string is a numeric value. Then, you can safely cast it to a Double or an Integer. In fact, you can cast it to both and then compare them against each other. If they're the same, you've got an integer value. For example:
Sub GenerateCards()
Do
Players = InputBox("How many players? Please enter an integer.")
If IsNumeric(Players) Then
If CDbl(Players) = CLng(Players) And Players > 0 Then
' Integer > 0 entered. Exit loop...
Exit Do
End If
End If
Loop
End Sub

VB - Negative Number and Conditional Statement

Back again with another noob question that is bugging the crap out of me. I spent 2 days trying figure this one out. It seems that me and VB and negative numbers always have a misunderstanding.
I got everything else in the program for a fat percentage calculator to work except the conditional statement that SHOULD print out an error message if either the double conversion of two textbox strings is less than zero. However, even though I enter negative numbers for both when testing, the program skips over my Else error statement and calculates the two negative numbers anyway and gets some wholly ridiculous fat percentage number. It doesn't even seem as if it's just going through with the expressions if the "If-Then" part of the code as I did the math and the percentage answer does not match up.
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare variables
Dim dblCaloriesInFood As Double
Dim dblGramsOfFat As Double
Dim dblPercentageOfCaloriesFromFat As Double
Dim dblCaloriesFromFat As Double
'Always initialize lblLowInFat message as not visible when button is clicked
lblLowInFat.Visible = False
Try
'Converting textbox strings to double.
dblCaloriesInFood = CDbl(txtCaloriesInFood.Text)
dblGramsOfFat = CDbl(txtGramsOfFat.Text)
If dblCaloriesInFood Or dblGramsOfFat > 0 Then
'Calculate Calories from fat
dblCaloriesFromFat = dblGramsOfFat * 9
'Calculate percentage of calories from fat
dblPercentageOfCaloriesFromFat = dblCaloriesFromFat / dblCaloriesInFood
'Display percentage of calories from fat
If dblPercentageOfCaloriesFromFat >= 0 Then
lblMessage.Text = dblPercentageOfCaloriesFromFat.ToString("p")
Else
lblMessage.Text = String.Empty
End If
'Display low fat message
If dblPercentageOfCaloriesFromFat <= 0.3 And dblPercentageOfCaloriesFromFat > 0 Then
lblLowInFat.Visible = True
End If
Else
'really tried to make this message work but couldn't figure it out.
'why does it only display this message when zero is entered and not when
'negative numbers are entered. instead it just calculates the negative numbers
'as if they were whole positive numbers or something, not sure because the percentage
'is way off the charts when i enter negative numbers. can't figure this out.
MessageBox.Show("Either the calories or fat grams were incorrectly entered")
txtCaloriesInFood.Text = String.Empty
txtGramsOfFat.Text = STring.Empty
txtCaloriesInFood.Focus()
End If
Catch
'error message for invalid input
MessageBox.Show("Please enter a numeric value for calories in food & number of fat grams.")
txtCaloriesInFood.Focus()
End Try
End Sub
Your If statement is wrong. First, you need to test the two values separately. Second, you want both values to be greater than zero, so you should use And instead of Or (which means only one has to be greater than zero).
If dblCaloriesInFood > 0 And dblGramsOfFat > 0 Then