Convert Textbox value to Integer - vb.net

I have the following Integer variables
Dim sMaxAmount As Integer
Dim sMinAmount As Integer
I am trying to compare them with a TextBox field.
If (Convert.ToInt32(txtTransactionAmount) < sMinAmount And Convert.ToInt32(txtTransactionAmount) > sMaxAmount) Then
Although I am converting it to Integer I get exception
Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to
type 'System.IConvertible'.
What am I doing wrong?

Typo: use txtTransactionAmount.Text instead of txtTransactionAmount
If (Convert.ToInt32(txtTransactionAmount.Text) < sMinAmount AndAlso Convert.ToInt32(txtTransactionAmount.Text) > sMaxAmount)

Val(TextBox.Text) will convert the value of a TextBox to an Integer.
txtTotal.text= Val(txtPrice.text) * Val(txtQuantity.text)```

In addition to not using the Text property to get the string contained in the TextBox, there are two other problems with your code.
You are not validating the contents of the TextBox. If the user enters something that can't be converted to an integer, an exception will be thrown.
The test you are doing doesn't make sense given the names of the variables. The value in the TextBox can't be both less than the minimum and more than the maximum.
The following code uses Integer.TryParse to validate the contents of the TextBox and convert it to an Integer. It also checks that the value in greater than or equal to sMinAmount and less than or equal to sMaxAmount.
Dim amount As Integer
If Integer.TryParse(txtTransactionAmount.Text, amount) _
AndAlso amount >= sMinAmount AndAlso aamount <= sMaxAmount Then
'The Integer called "amount" now contains a value between sMinAmount and sMinAmount
End If

Related

Val() Not working correctly or not how it should

I am trying to get a "x" amount from the inputbox and use that value for value changing and the math does something weird and doesn't work correctly.
Dim infantry As Integer
infantry = InputBox("How many do you want to attack with?", "Choose how many:", , ,)
frmMainGame.lblHPAI.Text = (Val(frmMainGame.lblHPAI.Text) - infantry * 2).ToString("N0")
Before
Result
The inputted value was 1
Inputbox() returns a string. You need to convert it to an integer value before you assign it to infantry. Also this function supports overloads so you don't have to include the arguments you don't plan to use.
infantry = CInt(InputBox("How many do you want to attack with?", "Choose how many:"))
This will return an error however if the value entered is non numeric. You would need to use a try/catch or preferably validate the result before using it:
Dim infantry As Integer
Dim Result As String = InputBox("How many do you want to attack with?", "Choose how many:")
If IsNumeric(Result) Then infantry = CInt(Result) Else MsgBox("Enter a numeric value", MsgBoxStyle.Critical)
We use Integer.TryParse to get the inputted value (TryParse because we don't have control about what can be that value)
If the parsing is successful we retrieve the label value (using Parse because that value is under our control so should always be a valid int)
Finally we make the calculation and assign the label it's representation.
If the parsing fail we should handle that (error message, looping to get a new value, etc.)
For (possibly both) parsing you should take care of formatting and culture issues which will dictate what format is valid or not.
Dim input = InputBox("How many do you want to attack with?", "Choose how many:")
Dim infantry As Integer
If Integer.TryParse (input, infantry) Then
Dim hpai = Integer.Parse (frmMainGame.lblHPAI.Text, NumberStyles.AllowThousands, CultureInfo.InvariantCulture)
frmMainGame.lblHPAI.Text = (hpai - infantry * 2).ToString("N0")
Else
' handle not an int inputted case
End If

What is used for holding String values in vb.net

hi I would just like to ask
if Val(Textbox1.Text) is for holding values of integers.
what should I put when holding values for String??
Textbox1.Text is a string, so a simple string variable will work:
Dim s As String = Textbox1.Text
But, note that Val doesnt "hold" a value but is a function to convert a string to a value. And it always returns a Double, not Integer.
To convert a string to Integer use Convert.ToInt32 or CInt. When working with TextBoxes though where the user may enter illegal data such as "123foo45", you should test the contents to avoid an error:
Dim n As Integer
If Integer.TryParse(TextBox1.Text, n) Then
' text can parse, n holds the value
Else
' tell the user they entered bad info
End If

How to verify an Integer? VB.Net

How do verify a value entered in an input box is an integer? If it's not I want the input box to show up again no harm done. Thanks for any help in advance
Dim int As Integer
If Integer.TryParse("12345", int) Then
'use int variable it holds the converted value
End If
as #OneFineDay said you have to use Integer.TryParse, now to repeat the question untill it is an integer you can do this:
dim ans = As String
dim int As Integer
dim isInteger As Boolean = False
do While Not isInteger
ans = InputBox("Give me an Integer")
isInteger = Integer.TryParse(ans, int)
End do
''Here int holds an integer
It wouldn't be an input validation question without a Regex answer, so if you want to make it more complicated than it needs to be then you can use something like
Dim expression As New Regex("^-?\d+$")
If Not expression.IsMatch(textBox1.Text) Then
textBox1.Text = String.Empty
End If
The Regex pattern will look at all entered text, and match iff there is zero or one minus signs followed by at least one digit.
12345 represents text that you can either enter manually in quotes or can grab from an input box like this:
Integer.TryParse(InputBox("Enter integer here"),myInt) ,such that the input from the inputbox is the one that will be converted into the integer variable,this saves you memory no need to declare another variable.
The loop in #bto.rdz 's answer is quite handy though,especially if you want the user to enter an integer no matter what

If/else statement VB.Net

If txtNum1.Text <= 0 Or txtNum2.Text <= 0 Then
lblResult.Text = "Result Error: Enter in a number graeter than zero"
End If
I am new to programming. I am trying to create an if/else statement so that if the number in either text box is less than or equal to 0 it will display an error message and not crash.
You have to Parse the number in the .Text property as an integer.
so your If statement would be something like
If Int32.Parse(txtNum1.Text) <= 0 ....
if you plan on reusing that value multiple times in your code, you can extract it in a variable.
Also, as pointed out in the comments, you should check for invalid numbers, you can do so, with Int32.TryParse(value, number). So then, if the TryParse(..) method returns false, you can handle the case.
To know exactly how this method works, you can read this
But to make it quick value is the string you want to parse and number is the integer value that is parsed out of the string. The method itself returns a boolean (true if it was successfully parse, and false otherwise)
Use proper conversion from string to numbers
Dim res1 As Integer
Dim res2 as Integer
if Not Int.TryParse(txtNum1.Text, res1) then
lblResult.Text = "Enter a valid first number "
return
End If
if Not Int.TryParse(txtNum2.Text, res2) then
lblResult.Text = "Enter a valid second number "
return
End If
If res1 <= 0 OrElse res2 <= 0 Then
lblResult.Text = "Result Error: Enter numbers greater than zero"
End If
You need to convert the user input to a numeric value. The Text property of a textbox is a string not a number. And if you want to convert it you should be prepared to receive bad inputs (like a non numeric value).
The best approach is to use Int.TryParse that try to convert the value typed by your user in a number and if it fails returns false. If successful the converted number will be found in the second argument.
Notice also that you should use OrElse instead of Or because the former use short-circuit evaluation
I wish to warn you about another pitfall that seems to be evident from the error message. The VB compiler tried to help you converting the two strings in numbers. This is very bad from my point of view. You should take the responsability to handle this kind of conversions disabling the automatic conversion of the compiler. Go to the properties of your project, page Compile and set the Option Strict to ON. In this way the compiler would stop this automatic conversion and signal as error the textBox1.Text <= 0
something like this would be better,
you check if it is a int then check if it is zero or under
Dim value1, value2 As Integer
If not Integer.TryParse(txtNum1.text, value1) orelse value1 <= 0 OrElse not Integer.TryParse(txtNum2.text, value2) orelse value2 <= 0 Then
lblResult.Text = "Result Error: Enter in a number graeter than zero"
End If
your comparison won't work normally, you are not using the same types (string vs integer)
i'd rather use integer.tryParse
so the code becomes something like :
dim n1 as integer
dim n2 as integer
if integer.tryparse(txtNum1.Text,n1) and integer.tryparse(txtnum2.text,n2) then
If n1 <= 0 Or n2 <= 0 Then
lblResult.Text = "Result Error: Enter in a number graeter than zero"
End If
else
lblResult.Text = "please input numbers"
end if

how to i create a Username shortener?

I have an AD username called "lastname-132" in Textbox1, this string is 12 long, so i want to add the username in to Textbox2, but shortened, in the textbox2 i only have a string length of only 10 available due to other tools this program is using, so i don't want to convert it all the time manually and want to just convert it automatically with a onleave event.
Anyone any idea how to write this?
So the End Result should look like this.
'String length can be 20 max.
Textbox1.Text = "lastname-123"
'some code to convert it to this:
'String length 10 max. Numbers and the "-" should stay the same, but remove letters if necessary.
Textbox2.Text = "lastna-123"
Here's the concept:
Split string based on '-' into 2 strings
In the example above: 'lastname' and '123'.
Check the length of the first string and cut if it is too long
the program checks 'lastname' and finds that it is too long, then
cuts it into 'lastna'
Combine 'lastna' and '123' back into a string
I hope this helps
Without more information, this will assume that there can be multiple hyphens, the number can be of variable length, and you can change the maximum length of the string by changing one variable.
Dim username As String = "lastname-123"
Dim max As Integer = 10
Dim lindex As Integer = username.LastIndexOf("-")
Dim numberLength As Integer = username.Length - lindex
Dim number As String = username.Substring(lindex)
Dim justName As String = username.Substring(0, lindex)
If justName.Length + numberLength >= max Then
username = justName.Substring(0, max - numberLength) & number
End If
If you are concentrating only on the restriction of length of characters to be accepted then you can use
Maxlength
property of the Textbox.
Ex: Maxlength="10"
restricts the Textbox to accept only 10 characters.
Try to make it fit with for example substring manipulation. See http://msdn.microsoft.com/en-us/library/dd789093.aspx for more info.