If user inputs something else than an integer, program will not proceed but will give a message box telling there is an error.
Here is what I have now and it's not working:
Sub Validation0()
If IsNumeric(curBat) Then
' Here, it still could be an integer or a floating point number
If CLng(curBat) = curBat Then
Else
MessageBox.Show("Please enter a number greater than 0.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End If
End If
End Sub
Try to diversify your code
1) identify whether string is integer
2) then identify whether it is greater than 0
Sub Validation0()
If IsNumeric(curBat) Then
' Here, it still could be an integer or a floating point number
dim curBat2 as integer = Convert.ToInt32(curBat)
If curBat2 > 0 Then
Else
MessageBox.Show("Please enter a number greater than 0.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
End If
End If
End Sub
If you want to round off integer value then use
Math.Roundoff(curBat2)
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 have a task to make a calculation of selling price and cost value.
I don't know have any idea to make a good coding for exception.
Private Sub ButtonCalculate_Click(sender As Object, e As EventArgs) Handles ButtonCalculate.Click
Dim SellingPrice As Double
Dim CostValue As Double
Dim Commission As Double
Dim CommissionRate As Double = 0.2
If Me.TextBoxSellingPrice.Text <> "" Or Me.TextBoxCostValue.Text <> "" Then
Try
SellingPrice = Double.Parse(TextBoxSellingPrice.Text)
CostValue = Double.Parse(TextBoxCostValue.Text)
'Calculation
Commission = CommissionRate * (SellingPrice - CostValue)
'Display
Me.TextBoxDisplay.Text = Me.TextBoxName.Text
Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")
Catch
MessageBox.Show("Wrong Input", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MessageBox.Show("Please fill your data completely", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Output:
Figure 1
Using exception handling to check that data is correct isn't really the best practice. For a start, the performance of Try..Catch blocks is pretty poor compared to just using If..Then..Endif as there is a fair amount of stuff happening in the background with exceptions. In your case it wont make a major difference, but if the Try..Catch..End Try is in a loop, your program can take quite a performance hit.
There is little else to do other than to write some If..End If statements to validate your input data .. As other commenters had stated, using .TryParse is an exellent way to start things off ..
If Not Double.TryParse(TextBoxSellingPrice.Text, SellingPrice) Or Not Double.TryParse(TextBoxCostValue.Text, CostValue) Then
MessageBox.Show("Invalid input. Please enter positive numbers only")
Exit Sub
End If
If SellingPrice < CostValue Then
MessageBox.Show("Selling Price must be greater than cost")
Exit Sub
End If
If Not SellingPrice > 0 Or Not CostValue > 0 Then
MessageBox.Show("Selling price and cost must be >0")
Exit Sub
End If
'Calculation
Commission = CommissionRate * (SellingPrice - CostValue)
'Display
Me.TextBoxDisplay.Text = Me.TextBoxName.Text
Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")
You could also have a look at the ErrorProvider component
I recently coded a program on VB.NET that shows Input1 Mod Input2 for example. Here i use function :
Private Function remainder(intno1 As Integer, intno2 As Integer) As Integer
Dim intresult As Integer
intresult = intno1 Mod intno2
remainder = intresult
End Function
Then i called it on Button_Click event :
Dim intm As Integer, intn As Integer
Dim intmod As Integer
intm = Val(TextBox1.Text)
intn = Val(TextBox2.Text)
If TextBox1.Text >= TextBox2.Text Then
MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
**Stop statement**
End If
intmod = remainder(intm, intn)
RichTextBox1.Text = "The result is " & Str(intmod)
as you can see on this code, i use if statements when txt1 is bigger or equals txt2 then message box shows. before End If clause i want to use statement that stop running the code. i mean stop doing those process on Function.
I use Stop and End statements but after i debug the program, it stop responding or even exit the program.
What should i do exactly here ?
You would use an Exit Sub call to stop executing that routine right there. If it had been a function, Exit Function
BTW, you should use CInt rather than Val to force to integer and your message should be more helpful (i.e., what was the error while computing?). Something along the lines of "First integer must be less than the second" would be more useful to a user.
Try one of these to exit a method
Exit Sub
Or
Return
Simple use :
Dim intm As Integer, intn As Integer
Dim intmod As Integer
intm = Val(TextBox1.Text)
intn = Val(TextBox2.Text)
If TextBox1.Text >= TextBox2.Text Then
MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
Exit Sub
End If
intmod = remainder(intm, intn)
RichTextBox1.Text = "The result is " & Str(intmod)
when you want exit from a function without return any value, It shows the software failure , and must not give the impression of 'business as usual' to the responsible caller code.
for this you need Throw an exception:
Throw New Exception("Error while computing proccess ! Please try Again.")
in this case the exception its not a suprise, it is likely command will be executed inadvertentlyexecuted inadvertently when the input text-boxes not correspond to expectations.
In this case there is no reason to throw an error, but has prevented the execute function already in the code caller, not in the function body.
I need to validate that the value in a particular cell in my datagridview falls within a certain range (0 - 99.9999) and if not, cancel the user edit. What I have so far is validating a column that it is a double data type and that it is > 0. That works. But now I need to validate each particular cell in that column since they all will need to be validated for particular numeric ranges. Each cell will have a different range of values it can accept.
Private Sub dgvPidVals0_cellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles dgvPidVals0.CellValidating
'Me.dgvPIDStatus0.Rows(e.ColumnIndex).ErrorText = ""
Dim newDouble As Double
Select Case e.ColumnIndex
Case 1
If Not Double.TryParse(e.FormattedValue.ToString(), newDouble) OrElse newDouble < 0 Then
e.Cancel = True
MessageBox.Show("PID Parameters values must be non-negative numeric values only!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
dgvPidVals0.CancelEdit()
If dgvPidVals0.Rows(5).Cells(1).Value > 99.9999 Then
e.Cancel = True
MessageBox.Show("Output Filter Value must be less than 100.0!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
dgvPidVals0.CancelEdit()
End If
End If
End Select
End Sub
Tez, I've already tried that exact code and it doesn't work. I'm stumped as to why not. The first If statement of the code works fine. The Else If portion does not work. I punch in a value greater than 100 in the DGV's cell and it takes (when it should not). I then click on the form again, and the Message box appears. I can't do anything at that point since every click of the DGV will make the message box show up. In the end, I used the CellEndEdit event handler to check that values in each of the cells that I'm evaluating fall within a certain range. It's a hacked way of doing it I think and I would think there is a better, more clean way of doing it. But....it works. Still open to answers from others as to what to do or if using the CellEndEdit event is the actual way to do it.
Private Sub dgvPidVals0_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgvPidVals0.CellEndEdit
If dgvPidVals0.Rows(0).Cells(1).Value > 6.14 Then
dgvPidVals0.Rows(0).Cells(1).Value = axis0Parameters(61) 'Load previous value into the cell
MessageBox.Show("Proportional Gain Value must be <= 6.14!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If dgvPidVals0.Rows(1).Cells(1).Value > 58.94 Then
dgvPidVals0.Rows(1).Cells(1).Value = axis0Parameters(62)
MessageBox.Show("Integral Gain Value must be <= 58.94!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If dgvPidVals0.Rows(2).Cells(1).Value > 0.1753 Then
dgvPidVals0.Rows(2).Cells(1).Value = axis0Parameters(63)
MessageBox.Show("Differential Gain Value must be <= 0.1753!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If dgvPidVals0.Rows(3).Cells(1).Value > 5 Then
dgvPidVals0.Rows(3).Cells(1).Value = axis0Parameters(64)
MessageBox.Show("Feed Forward Value must be <= 5!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If dgvPidVals0.Rows(4).Cells(1).Value > 1.5 Then
dgvPidVals0.Rows(4).Cells(1).Value = axis0Parameters(65)
MessageBox.Show("Rate Feed Forward Value must be <= 1.5!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If dgvPidVals0.Rows(5).Cells(1).Value > 100 Then
dgvPidVals0.Rows(5).Cells(1).Value = axis0Parameters(39)
MessageBox.Show("Output Filter Value must be <= 100.0!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
slider1.Value = dgvPidVals0.Item(1, 0).Value
slider2.Value = dgvPidVals0.Item(1, 1).Value
slider3.Value = dgvPidVals0.Item(1, 2).Value
slider4.Value = dgvPidVals0.Item(1, 3).Value
slider5.Value = dgvPidVals0.Item(1, 4).Value
slider6.Value = dgvPidVals0.Item(1, 5).Value
End Sub
Good afternoon all, I am beginning my first forays into programming and have decided to begin with VB.net as I can get VS2010 professional free through MS Dreamspark program.
I have been following some basic tutorials online and am now writing a small program that runs a loop to add all the numbers together between two numbers input by the user.
Below is the code I have written:
Public Class Form1
Private Sub cmdAddNumbers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNumbers.Click
Dim NumberOne As Integer
Dim NumberTwo As Integer
Dim Result As Integer
Dim i As Integer
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf txtNumberTwo.Text > NumberOne And IsNumeric(txtNumberTwo.Text) Then
NumberTwo = txtNumberTwo.Text
End If
For i = NumberOne To NumberTwo
Result = Result + i
Next i
txtResult.Text = Result
txtNumberOne.Clear()
txtNumberTwo.Clear()
End Sub
End Class
Now, I am wondering if I have written the most efficent If statements to execute this code or if they can be written any simpler with AND/OR statements to possibly remove some of the ElseIf's.
Any insight is greatly appreciated.
Thank you,
Alex
You should start with putting Option Strict On at the top of your code to force yourself to write code without implicit conversions between strings and numbers. An example of a pitfall in your code is where you compare the string value txtNumberTwo.Text to the numeric value NumberOne; it isn't obvious if the string is converted to a number so that the comparison works properly, or if the number is converted to a string so that it does a string comparison instead.
You can use the Int32.TryParse method to parse each number only once instead of three times:
Dim numberOne As Integer
Dim numberTwo As Integer
Dim result As Integer
If Not Int32.TryParse(txtNumberOne.Text, numberOne) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf numberOne <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
If Not Int32.TryParse(txtNumberTwo.Text, numberTwo) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
ElseIf numberTwo < numberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
End If
Your loop is not needed at all. You can calculate the sum directly:
Result = (numberOne + numberTwo) * (numberTwo + 1 - numberOne) / 2
What about:
If Not IsNumeric(txtNumberOne.Text) Or txtNumberOne.Text <= 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
Else
NumberOne = txtNumberOne.Text
End If
If Not IsNumeric(txtNumberTwo.Text) Or txtNumberTwo.Text < NumberOne Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Exit Sub
Else
NumberTwo = txtNumberTwo.Text
End If
Be aware that if NumberOne is equal to Textbox2.Text, NumberTwo is never assigned
i think the best solution for you is just set the textboxes to be able to accept only numbers, that way you can avoid all the checks if the texts is numeric or not and only check if its bigger than zero.
to set the textboxes to accept only numbers copy this function:
Private Function TrapKey(ByVal KCode As String) As Boolean
If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
TrapKey = False
Else
TrapKey = True
End If
End Function
and in the keypress event of the textboxes add
e.Handled = TrapKey(Asc(e.KeyChar))
If Not IsNumeric(txtNumberOne.Text) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text = 0 Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Exit Sub
ElseIf txtNumberOne.Text > 0 And IsNumeric(txtNumberOne.Text) Then
NumberOne = txtNumberOne.Text
End If
The third If is superflious. We know it must be IsNumeric, as it passed the first If, and we know it cannot be 0, as it passed the second If. (You also make no allowances at all, if it happens to be negative)
Now, it been a while since I last did VB.Net, but I'm pretty sure it still have a distinct between strings & integers, which means txtNumberOne.Text = 0 shouldn't even compile.
And also, why are you making your users guess what a "valid number" is?
Dim numberOne as Integer
If IsNumeric(txtNumberOne.Text) Then
numberOne = CInt(txtNumberOne.Text)
else
numberOne = -1;
End If
If numberOne < 1
MsgBox("Please Enter A Positive Number For Number One")
txtNumberOne.Clear()
Exit Sub
End If
Dim doub As Double
If Not (Double.TryParse(txtNumberOne.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number One")
txtNumberOne.Clear()
Else
NumberOne = doub
End If
If Not (Double.TryParse(txtNumberTwo.Text, doub) AndAlso doub > 0) Then
MsgBox("Please Enter A Valid Number For Number Two")
txtNumberTwo.Clear()
Else
NumberTwo = doub
End If
I think this is waht you are looking for
Result = (NumberTwo * (NumberTwo + 1) / 2) - ((NumberOne - 1) * (NumberOne) / 2)