I have a program where the user enters a quantity in a field and the price is automatically calculated. I want to only allow numbers in this field and can't figure out a way to do so.
All I Currently have is a small pop up message that occurs when a user enters a number over 1000. But it still lets them go through with it if they just click okay.
Private Sub txt2x6LumberQuantity_TextChanged(sender As Object, e As EventArgs) Handles txt2x6LumberQuantity.TextChanged
'Text changed event that occurs when the text within the textbox is changed'
'If statement to check if the number is between 0 and 1000, if is it'll go to the next block of code and if not goes to the else'
If IsNumeric(txt2x6LumberQuantity.Text) = True Then
Select Case CInt(txt2x6LumberQuantity.Text)
Case 0 To 1000
'Calculates line total with a function'
dec2x6LumberLineTotal = calculate2x6LumberLineTotal(CDec(lbl2x6LumberPrice.Text), CDec(txt2x6LumberQuantity.Text), lbl2x6LumberLineTotal)
'Calculates the subtotal'
calculateSubtotal(dec2x6LumberLineTotal, dec2x4LumberLineTotal, decOneHalfPlywoodLineTotal, decFiveEighthsPlywoodLineTotal, decNailsLineTotal, decBradsLineTotal, decGalvanizedScrewLineTotal, decSledgeHammerLineTotal, decFiveDrillBitsLineTotal, decStapleGunLineTotal)
'Calculates the tax'
calculateTax(decSubtotal)
Case Else
MsgBox("Choose a quantity between 0 and 1000", MsgBoxStyle.Information, "Quantity entered is invlaid.")
txt2x6LumberQuantity.Focus()
End Select
End If
End Sub
Example:
USING THE VALIDATE EVENT PROCEDURE
Private Sub txtAge_Validate(Cancel As Boolean)
If Not IsNumeric(txtAge.Text) Then
Cancel = True
ElseIf txtAge.Text < 21 Then
Beep 'give the user some minimal feedback
MsgBox "Enter an age greater than 21"
Cancel = True
'Following is not needed. Placed here for clarity
Else
Cancel = False
End If
End Sub
Related
private Sub Command1_Click()
a = InputBox("What is the Number ?", "Input Example"," ")
If a = "-1" Then
End If
End Sub
the whole question is: Enter some numbers until a negative value is entered to stop the program(stop running the what is your number thing). then find the average of the entered numbers.
What I want to do, for now, I want to know how can I make my "a" variable accept any negative value like in the code above it stops when I enter -1 but I want to stop when I enter -3, -10, or any negative value.
There are some helpful answers down below
If you are expecting the usual input to be text then you can use the Double.TryParse method to check if a number was entered. If it was, then you can check if that number is negative, and exit the application if so:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700)
If userMsg <> "" Then
Dim x As Double
If Double.TryParse(userMsg, x) AndAlso x < 0 Then
Application.Exit()
End If
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The AndAlso operator only looks at the second argument if the first evaluated to True.
If you would like to repeat some portion of code till specific condition is met, you need to use:
While...End While Statement (Visual Basic)
or
Do...Loop Statement (Visual Basic)
It's also possible to write conditional loop using For... Next statement
Dim myNumber As Integer = 0
Dim mySum As Integer = 0
Dim myCounter As Integer = 0
Do
Dim answer As Object = InputBox("Enter integer value", "Getting average of integer values...", "")
'check if user clicked "Cancel" button
If answer <> "" Then
'is it a number?
If Int32.TryParse(answer, myNumber)
If myNumber >=0 Then
mySum += myNumber
myCounter += 1
Else
Exit Do
End If
End If
End If
Loop
Dim average As Double = mySum/myCounter
'you can display average now
Tip: Do not use InputBox, because this "control" is VisualBasic specific. Use custom Form instead. There's tons of examples on Google!
I'm trying to get return false when a/b where b is equal to 0 so that my error message appears to the user. So far I've managed to do a check within my sub but I need the check to be within the function. Currently, I get a infinity as the result, when for example 7 is divided by 0. I've basically made a pretty basic calculator and would appreciate any help.
Function:
Private Function validationCheck() As Boolean
' The following checks if the two fields are numerical values, are not blank and if the 2nd number is not zero
'The latter is for the purpose of division
'If the fields meet the above conditions then true is returned
'Else if either one is not met, then false is returned
If IsNumeric(txt1stNumber.Text) And txt1stNumber.Text <> "" And IsNumeric(txt2ndNumber.Text) And txt2ndNumber.Text <> "" Then
Return True
Else
Return False
End If
End Function
Division Sub
Private Sub btnDivide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDivide.Click
'The following sub is the code for the division button.
'First it checks whether false is returned from the ValidationCheck funtion
'If so, an error message is shown
'Else if true is returned, then the values are divided together to form the result
If validationCheck() = False Then
MsgBox("Please enter a numerical value for both fields. Also, field cannot be left blank.")
ElseIf validationCheck() = True Then
lblResult.Text = Val(txt1stNumber.Text) / Val(txt2ndNumber.Text)
End If
You can add one more condition into you function to evaluate txt2ndNumber.Text like this, then if the number b is 0 or 00 like this this will also return false.
Private Function validationCheck() As Boolean
If IsNumeric(txt1stNumber.Text) And txt1stNumber.Text <> "" And IsNumeric(txt2ndNumber.Text) And txt2ndNumber.Text <> "" Then
Dim number As Double = txt2ndNumber.Text
If number = 0 Then
Return False
Else
Return True
End If
Else
Return False
End If
End Function
Private Sub txt_dd_sku12_beforeUpdate(Cancel As Integer)
''start data validation by (len), (numeric) ''
If Len(Trim(txt_dd_sku12)) <> 12 Then
txt_dd_sku12.BackColor = RGB(116, 174, 244)
MsgBox ("the entry must be a 12 Digit SKU only")
Cancel = True
Exit Sub
End If
If Not IsNumeric(Trim(txt_dd_sku12)) Then
MsgBox " Highlighted field can not be blank. entry DD'S Sku12 to proceed further"
txt_dd_sku12.BackColor = RGB(116, 174, 244)
Cancel = True
Exit Sub
End If
End Sub
i have a 5 textboxes the i have to validate by, before update insert in my table when i press enter in my last textbox, but if i go back to an early textbox dont insert data until i press enter.
only numbers
not empty
no more or less of 12 digits
What your are looking for is the forms before update event. That will keep you from moving to a new record until your individual field requirements have been met.
Public Function ValidField(ctl as Control, FieldLength as integer) as Boolea
If Not IsNumeric(ctl) then
MsgBox "Highlighted field can not be blank. Enter an appropriate text."
ctl.backColor = RGB(116, 174, 244)
DoCmd.CancelEvent
Exit Function
End if
if len(ctl) <> FieldLength or IsNull(ctl) or ctl = "" then
MsgBox "The entry must be a 12 digit sku only."
ctl.BackColor = RGB(116,174,244)
DoCmd.CancelEvent
Exit Function
End if
ValidField = true
End Function
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Not ValidField(txtBox1, 7) Then
Exit Sub
End If
End Sub
Change
If Len(Trim(txt_dd_sku12)) <> 12
To
If Len(Trim(txt_dd_sku12)) <> 12 And IsNumeric(Trim(txt_ss_sku12)) And Trim(txt_ss_sku12) <> vbNullString
I want my program to check whether the inputs in a TextBox meet certain condition. If the target condition is not met, the cursor should focus back on that particular TextBox.
My code:
Private Sub ButtonSubmit_Click(sender As Object, e As EventArgs) Handles ButtonSubmit.Click
EnterVotes.LabelCan1.Text = CandName1.Text
EnterVotes.Labelcan2.Text = CandName2.Text
EnterVotes.LabelCan3.Text = CandName3.Text
EnterVotes.LabelCan4.Text = CandName4.Text
EnterVotes.LabelCan5.Text = CandName5.Text
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
End If
loading.Show()
Me.Hide()
If CandName1.Text = "" Then //Show your message here // CandName1.focus()//to return to that textbox Else //Show your
message here End If
use the method focus() to return and re-write into that textbox
It is actually quite simple
just check if the value of the text is > 1
then put focus on the textbox
heres an example
if txtbox.text.value < 1 then
messagebox.show("You must enter data for textbox")
txtbox.focus()
end if
and then continue method for each text box you are working with
Could get fancy and use some linq to go threw your names.
Dim Candidate() As TextBox
Candidate = Me.Controls.OfType(Of TextBox)().Where(Function(c) c.Name.Contains("CandName")).ToArray()
Dim i As Integer = 0
While i < Candidate.Count
If(Candidate(i).text.value < 1)
MessageBox.Show("Please enter a name in Candidate " & (i + 1).ToString())
Candidate(i).Focus()
Exit While
End If
i += 1
End While
This way you can check all your candidates in one shot. This is untested code, but I think it should work.
You can play around with this and edit however you please it's pretty flexible at this point.
I think this might be the way but not very efficient.
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Else
CandName2.Focus()
End If
If CandName2.Text = "" Then
MessageBox.Show("Please enter an name in Candidate 2")
CandName3.Focus()
Else
CandName3.Focus()
End If
If CandName3.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 3")
CandName3.Focus()
Else
CandName4.Focus()
End If
If CandName4.Text = "" Then
MessageBox.Show("Please enter a name in candidate 4")
CandName4.Focus()
Else
CandName5.Focus()
End If
If CandName5.Text = "" Then
MessageBox.Show("Pleae enter a name in candidat 5")
CandName5.Focus()
Else
loading.Show()
End If
If String.IsNullOrWhitespace( CandName1.Text ) Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Return
End If
... for all five
loading.Show()
Me.Hide()
You want to make sure to exit this early with the Return statements so you don't get to the code:
loading.Show()
Me.Hide()
I am having some problems with an assignment. The case project is:
Create an application that allows the user to guess a random number generated by the computer. When the user makes an incorrect guess, the application should move an image either upr or down, depending on how the guess compares to the random number. If the random number is greater than the user's guess, the application should move the image up to indicate that the user needs to guess a higher number. If the random number is less than the user's guess, the application should move the image down to indicate that the user needs to guess a lower number. The game ends when the user guesses the random number. However, the application should allow the user to stop the game prematurely. When that happens the application should siplay the random number.
I have tried every which way I can think of including using a textbox instead of an inputbox and playing around with the syntax - but just can't seem to get it right. Advice would be much appreciated. Thanks.
My code:
Public Class Form1
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Number As Integer
Dim inputNumber As Integer
Dim answer As Integer
Dim isconverted As Boolean
Dim computerchoice As New Random
answer = computerchoice.Next(1, 20)
inputNumber = InputBox("Please guess number", "Random Number Game")
Do
isconverted = Integer.TryParse(inputNumber, Number)
If isconverted = True Then
If answer = Number Then
MessageBox.Show("You Win")
ElseIf answer > Number Then
PictureBox1.SetBounds(0, 90, 0, 0, BoundsSpecified.Y)
ElseIf answer < Number Then
PictureBox1.SetBounds(0, 220, 0, 0, BoundsSpecified.Y)
End If
Else
MessageBox.Show("Please enter a valid number between 1 - 20 only")
End If
inputNumber = InputBox("Please guess number", "Random Number Game")
Loop While answer <> Number
MessageBox.Show("Answer:" & answer.ToString)
End Sub
End Class
Your code actually almost worked. A few things though:
The only thing that really didn't work was the picture moving up and down. All you have to do for that is to increment/decrement the .Top property.
Because you converted your input to a number at the beginning of the loop and not evaluating till the end, you were looping through an extra time after you got the right answer.
The number comparison after the conversion was redundant, since you know they got the number if they exit the loop.
If you're new to Visual Studio and don't know about breakpoints and other debugging, it is worth it to look into those. With these tools you can pause your code at given points in your program, look at the values variables hold, and step through your code line-by-line.
Here's the working code:
Do
If isconverted = True And Number >= 1 And Number <= 20 Then
If answer > Number Then
PictureBox1.Top -= 10
ElseIf answer < Number Then
PictureBox1.Top += 10
End If
Else
MessageBox.Show("Please enter a valid number between 1 - 20 only")
End If
inputNumber = InputBox("Please guess number", "Random Number Game")
isconverted = Integer.TryParse(inputNumber, Number)
Loop While (answer <> Number)
MessageBox.Show("You Win! The answer is " & answer.ToString)