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
Related
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
Below is the snippit of code that is having the trouble.
Private Const DOB_VALUE As Integer = 0
Private Const ADDRESS_VALUE As Integer = 1
Private Const NAME_VALUE As Integer = 2
For Each oRecord As KeyValuePair(Of Integer, String) In OriginalFileInfo
For Each nRecord As KeyValuePair(Of Integer, String) In WorkingFileInfo
Dim OriginalComparisonStringSubstrings As String() = oRecord.Value.ToString.ToLower.Split(":")
Dim WorkingComparisonStringSubstrings As String() = nRecord.Value.ToString.ToLower.Split(":")
' Are dates of birth the same?
If OriginalComparisonStringSubstrings(DOB_VALUE) Like WorkingComparisonStringSubstrings(DOB_VALUE) Then
' Are the address the same?
If OriginalComparisonStringSubstrings(ADDRESS_VALUE) Like WorkingComparisonStringSubstrings(ADDRESS_VALUE) Then
' Dob and address are the same, means we have a valid match. Lets check if the names match
If OriginalComparisonStringSubstrings(NAME_VALUE) Like WorkingComparisonStringSubstrings(NAME_VALUE) Then
' dob, address and name matches
Else
' Dob and address matches, name does not
End If
End If
End If
Next
Next
The issue is, when I get to the address value comparison, it is always failing. I have had my watch window active and the values are identical yet they do not compare. You can see my Watch window output below.
- WorkingComparisonStringSubstrings {Length=3} String()
(0) "4323" String
(1) "123 somewhere lane" String
(2) "j ii" String
- OriginalComparisonStringSubstrings {Length=3} String()
(0) "4323" String
(1) "123 somewhere lane" String
(2) "j ii j. .johnson" String
OriginalComparisonStringSubstrings(DOB_VALUE) Like WorkingComparisonStringSubstrings(DOB_VALUE) True Boolean
OriginalComparisonStringSubstrings(ADDRESS_VALUE) Like WorkingComparisonStringSubstrings(ADDRESS_VALUE) False Boolean
OriginalComparisonStringSubstrings(NAME_VALUE) Like WorkingComparisonStringSubstrings(NAME_VALUE) False Boolean
The comparison for the two addresses, which would be ("123 somewhere lane" Like "123 somewhere lane") should be true but is returning false. My question is why are these values failing in comparison when they are so apparently equal? In my code I am using "Like" comparisons but I have also tried String.Compare, StrComp, .Equals, =, and every other variation of comparison. In addition, the values are always a string from the time they are inserted into the FileInfo variable to the time they are split and compared.
Anyone have an idea of why they wont compare?
My colleague pointed out the issue. In the previous version of the program, we were dynamically changing the value of ADDRESS_VALUE. In this most recent version is when we changed the the values to a constant integer.
It appears in this version, before we made ADDRESS_VALUE constant, it was still being assigned a new value, so it was actually comparing the NAME_VALUE rather than comparing the ADDRESS_VALUE which would in fact fail.
Thank you everyone for your comments. They were really helpful.
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
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.
i have a string "<PinX F='53mm'></PinX>", I want to access the 53 within the string and do some addition to it and then add the answer back into that string. I've been thinking about this and wasn't sure whether this can be done with regular expression or not? Can anybody help me out.
thanks
Yes, you can use a regular expression. This will get the digits, parse them to a number, add one to it, and put it back in the string (that is, the result is actually a new string as strings are immutable).
string s = Regex.Replace(
input,
#"(\d+)",
m => (Int32.Parse(m.Groups[1].Value) + 1).ToString()
);
Take a look at the HTML Agility Pack.
A regular expression looks like a good fit for this particular problem:
\d+
Will match one or more digits.
Int32.Parse(Regex.Match("<PinX F='53mm'></PinX>", #"\d+").Value)
Will return 53.
In this single case yes. "'(.*?)' then access the first group, but if this is part of a larger xml regular expressions should not be used. You should utilize the xml parser build into .net find the attribute with xsd and get the value.
Alternatively, here's a small routine...
' Set testing string
Dim s As String = "<PinX F='53mm'></PinX>"
' find first occurence of CHAR ( ' )
Dim a As Integer = s.IndexOf("'")
' find last occurence of CHAR ( ' )
Dim b As Integer = s.LastIndexOf("'")
' get substring "53mm" from string
Dim substring As String = s.Substring(a, b - a)
' get integer values from substring
Dim length As Integer = substring.Length
Dim c As Char = Nothing
Dim result As String = Nothing
For i = 1 To length - 1
c = substring.Chars(i)
If IsNumeric(c) Then
result = result & c
End If
Next
Console.WriteLine(Int32.Parse(result))
Console.ReadLine()