I have 2 separate functions, each one returns its own string value.
I am wanting to check that both return a specific string value and if they do then perform a task.
Example:
If function Apples returns "Apples" and Function Pears () returns "Pears" then do something
I am currently using 2 nested If statements and I want to know if this is the best way to do it.
If Apples() = "Apples" Then
If Pears() = "Pears" Then
"Do something here"
End If
End If
Using ANDALSO, if the first comparison fails, the second comparison is not made:
If String.Compare(Apples(),"Apples", True) = 0 ANDALSO String.Compare(Pears(),"Pears", True) = 0 Then
'Do Something Here
End If
Be careful with string comparisons, the comparison is case sensitive. "Apples" <> "APPLES".
Another version:
If Apples().ToUpper = "APPLES" ANDALSO Pears().ToUpper = "PEARS" Then
'Do Something Here
End If
Related
in VB.NET I have TextBox with masked time input such as
__:__
Before I save this to SQL database I have a conversion to iso format like:
Dim MyTime As DateTime = DateTime.ParseExact(txtMyTime.Text, "HH:mm", Nothing)
Dim isoMyTime As String = MyTime.ToString("HH:mm:ss")
Now my question is how to write to database Null value if this text box is empty without time value input?
not sure if you are stuck on SQL, or to figure out wether the textbox has been given a value.
when you write to database, you define the columns that you want to write to:
insert into Table1(Forename, Surname)
values(John, Jehnson)
if you want the surname to be null, simply do not mention it:
insert into Table1(Forename)
values(John)
Make sure your column is designed to allow nulls.
to figure out if the textbox has a value, simply Check if the values matches a actual valid format
solution 1
you can achieve this with a Regex:
[0-9]{2}:[0-9]{2}
this regex makes sure that there are 2 numbers before and after the : sign.
solution 2
You can also replace the textbox with 2 numericupdown controls.
solution 3
another option is to try to parse it manually.
dim ISvalid as boolean = true
if textbox1.contains(":")
if split(textbox1, ":").count = 2
if split(textbox1, ":").first.length = 2 andalso split(textbox1, ":").last.length = 2
if IsNumeric(split(textbox1, ":").first) andalso isnumeric(split(textbox1, ":").last
' this is a valid value
else
isvalid = false
end if
else
isvalid = false
end if
else
isvalid = false
end if
else
isvalid = false
end if
if isvalid then
Dim MyTime As DateTime = DateTime.ParseExact(txtMyTime.Text, "HH:mm", Nothing)
Dim isoMyTime As String = MyTime.ToString("HH:mm:ss")
end if
I've seen plenty of questions here about strings that are equal returning as unequal, but trust me to not get that problem.
I have this function.
Protected Sub ChkValidStockCode()
If Not (Voucher.ValidStockCode = "") Then
Dim validcount As Int32 = 0
Dim validproduct As String = Product.GetProductNameByCode(Voucher.ValidStockCode)
For Each rpi As RepeaterItem In rptCart.Items
Dim ProductID As HyperLink = CType(rpi.FindControl("hlProductID"), HyperLink)
Dim ProductName As HyperLink = CType(rpi.FindControl("hlProductName"), HyperLink)
If (String.Compare(Voucher.ValidStockCode.ToString(), ProductID.ToString())) Then
validcount = validcount + 1
End If
Next
If validcount = 0 Then
txtVoucher.Text = "Sorry, this voucher is only valid when purchasing a " & validproduct
failed = True
Exit Sub
End If
End If
End Sub
It's supposed to compare the two strings and increment a validcount integer if they're equal, and then tell you off if it gets to the end of the repeater without finding any matches.
The variables in this test are LT00004 (Voucher.ValidStockCode) and SP08076 (ProductID.ToString())
I have run the code several times, outputting the different strings as the result and can confirm they are what they should be, but when I try to compare them (and I expect validCount to be 0), they return as a match.
What did I do to screw this up?
You probably want String.Equals() and not String.Compare(). Compare is used to order things and not test for equality. What's happening is String.Compare is returning a non-zero number so the condition is being satisfied. The reason for that is because in VB "0" is False but any non-zero number evaluates to true. There's a whole history behind why that's the case but I digress.
how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.
say I wanted the following code:
Sub X
If TextBox1.Text = "Value" then
' Do something
ElseIf TextBox1.Text = "Value1" then
' Also do some other code
End IF
End Sub
How would I do this?
I would like the program to check something first, and if that is true then check something else, and if that is true, also execute that code.
Are you looking for AndAlso?
If TextBox1.Text = "Value" AndAlso TextBox2.Text = "Value1" Then
....
End If
The AndAlso operator performs a logical operation between the two sides of the expression. It evaluates the first condition and if this condition is false it stop further processing (without evaluating the second expression). Only if both conditions are true the code inside the if is executed. This behavior is called short-circuiting evaluation
However, the code in your question cannot be evaluated as true in both conditions for the same TextBox1
If condition1
then
if condition2
then
// do something
end if
end if
If the example in your code is valid, equals value1 then equals value2, do you mean you want if either, because it cannot be both equal?
In this case you can use OR.
Instead of else-if, do:
If TextBox1.Text = "Value" then
' Do something
end if
If TextBox1.Text = "Value1" then
' Also do some other code
End IF
or:
If TextBox1.Text = "Value" then
' Do something
If TextBox1.Text = "Value1" then
' Also do some other code
End IF
end if
Depending on whether you want to execute B only if A is also true.
I am taking a VBA class and am completely stuck on this problem. We CANNOT use the masked text box, which would solve this problem. Instead the professor actually wants me to learn the code, can you imagine?
All kidding aside, the user needs to enter a gas price into a text box, then hit calculate to receive the total cost of the trip. There is much more to the interface but will spare you the details. If a user enters anything else number than a positive number with one decimal place, it should return an error. I have figured out 0 or 0000 as well as a negative number such as -3.45. Now I have to get any text or special characters to give me an error as well as something like 34.56.12.45. You never know, a user may feel the need to type in their IP address. The key to the assignment is that I catch all probable user errors.
Here is what I've written for the calculation as well as catch the errors. I have tried the Try/Catch statements as well. Nothing worked but I got the first two parts of the IF statement to work yet always failing on the last IF part until it gets to the calculation.
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim Mileage As Decimal
Dim Miles As Decimal
Dim GasPrice As Decimal
Dim Cost As Decimal
If CDec(txtbxGasPrice.Text) = 0 Then
MessageBox.Show("Please enter a positive dollar amount")
txtbxGasPrice.Text = String.Empty
End If
If CDec(txtbxGasPrice.Text) < 0 Then
MessageBox.Show("Please enter a positive dollar amount")
txtbxGasPrice.Text = String.Empty
End If
If Cost = CDec((Miles / Mileage) * GasPrice) Then
Miles = CDec(lblTMiles.Text)
Mileage = CDec(lblMileage.Text)
GasPrice = CDec(txtbxGasPrice.Text)
lblTotalCost.Text = Cost.ToString("C2")
End If
If CBool(txtbxGasPrice.Text = "") Then
MsgBox("You must enter a dollar amount")
End If
*If Not IsNumeric(txtbxGasPrice.Text) Then
MessageBox.Show("Please enter a positive dollar amount")
txtbxGasPrice.Text = String.Empty*
End If
End Sub
'I have placed this at the top, in the middle, at the bottom but no luck. What am I missing?
Appreciate your thoughts - Lauren
This one seems to meet your criteria and pass David's tests:
Function IsValid(txt As String) As Boolean
If Not IsNumeric(txt) Then
Exit Function
End If
If Len(txt) < 2 Then
Exit Function
End If
If Not Mid(txt, Len(txt) - 1, 1) = "." Then
Exit Function
End If
If Not txt > 0 Then
Exit Function
End If
IsValid = True
End Function
This seems like a perfect application of regular expressions, but could be out of scope for this problem, maybe even better though vb has a Decimal.TryParse(or parse) that will take a string and try to parse it to a decimal.
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
on a side not I'm not 100% sure how it acts with xx.xx.xx but I'm betting it will fail and help your problem
I'm going to expand on CSgoose's idea to use RegEx, it seems a lot more reliable. I am very, very green when it comes to using RegEx but I try to work on Q's here at SO, so this may not be the optimal pattern to match, but a function like this seems to do the trick when I test a few value.
0/0.0/0.00 = False
-1.5 = False
1.5 = True
5.45 = False
Steve = False
Steve.6 = False
Steve6.58 = False
6.574.2 = False
A value that evaluates to 0 will return false. Negative values return false. Value must have a decimal component, be comprised of any # of digits (this can be tweaked if you want to limit it, eg., to ##.# format, etc.). Matches full text only, so things like IP addresses won't return true, etc.
NOTE This is VBA, but should be easily adaptable for your purposes)
Sub YourSub()
If Not IsMatch(CStr(txtbxGasPrice.Text)) Then
MsgBox "Please ensure that the value you enter is a positive dollar amount, to 1 decimal place!", vbCritical, "Invalid Gas Price Value!"
End IF
End Sub
This function requires enabling reference to Microsoft VBScript Regular Expressions 5.5, or you could use late-binding.
Function IsMatch(str As String) As Boolean
'Tests for a positive numeric value, formatted 0.0 with a mandatory decimal component
' exact match only
Dim re As RegExp
Dim allMatches As MatchCollection
Dim retVal As Boolean
retVal = False 'by default
If Not IsNumeric(str) Then GoTo EarlyExit 'ignore any non-numeric value
Set re = New RegExp
re.Pattern = "\d*\.[0-9]"
Set allMatches = re.Execute(str)
If allMatches.Count = 1 Then
'If there are multiple matches, then I think safe to say it's not a match,
' make sure it's a full string match
If str > 0 Then
retVal = (allMatches(0) = str)
End If
End If
EarlyExit:
Set re = Nothing
IsMatch = retVal
End Function
Update to force, for example, ##.# format, you could do
re.Pattern = "[1-9]?\d\.\d"