If Statement that evaluates two conditionals if first is true? - vb.net

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.

Related

Comparing 2 Function String Results VB.Net

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

short if statement in VB.Net

Can i make short that my code IF statement in one single IF Statement?
If randomNumber = strWords2(StrwrVal.Text) Then
Else
If randomNumber = strWords3(StrwrVal.Text) Then
Else
If randomNumber = strWords4(StrwrVal.Text) Then
Else
If randomNumber = strWords5(StrwrVal.Text) Then
Else
TxtRnd1.Text = TxtRnd1.Text & vbNewLine & randomNumber
End if
End if
End if
End if
You should NEVER have an empty If block. If you don't want to do something if a condition is True, don't test whether that condition is True in the first place. Test for the inverse condition. In your case, you should be doing this:
If randomNumber <> strWords2(StrwrVal.Text) AndAlso
randomNumber <> strWords3(StrwrVal.Text) AndAlso
randomNumber <> strWords4(StrwrVal.Text) AndAlso
randomNumber <> strWords5(StrwrVal.Text) Then
TxtRnd1.AppendText(Environment.NewLine & randomNumber)
End if
Instead of a bunch of Else and If, or a bunch of ElseIf, you can use a Select Case. It's easier to read, among other things.
The Select Case will evaluate a variable and you can choose the outcome depending on what you find. You can also test for True if you want to evaluate things more complicated than one variable.
Select Case randomNumber
Case strWords2(StrwrVal.Text)
'some code
Case strWords3(StrwrVal.Text)
'some other code
Case strWords4(StrwrVal.Text)
'you got the idea
Case Else
TxtRnd1.Text = TxtRnd1.Text & vbNewLine & randomNumber
End Select
For what I read this would be the cleanest answer, but it always depends on the algorithm. Have fun!

weird IF statement error " Conversion from string "FAIL" to type 'Long' is not valid."

I'm basically running through rows in a table. I'm checking each row to see if at least 1 of the columns im interested is = "pass" and that the rest = either "pass" or "N/A".
But im getting an error:
"An exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll but was not handled in user code
Additional information: Conversion from string "FAIL" to type 'Long' is not valid."
The statuses can either be "PASS", "FAIL", OR "N/A" in the DB is you're wondering where the FAIL came from.
Here's the code:
Private Function HasAuditPassed(activeLotId As String) As Boolean
Dim sql = String.Format("SELECT STEPID, CAVITYPAIRASTATUS,CAVITYPAIRBSTATUS,CAVITYPAIRCSTATUS,CAVITYPAIRDSTATUS FROM " & _
"TB_BL_AMMSSTEPSTATUS WHERE AUDITLOT = '{0}'", activeLotId)
Dim dynaset = DB.CreateDynaset(sql, DBWrapper.DynasetOptions.ORADYN_READONLY)
Do Until dynaset.EOF
Dim cavityPairAStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRASTATUS")
Dim cavityPairBStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRBSTATUS")
Dim cavityPairCStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRCSTATUS")
Dim cavityPairDStatus = dynaset.GetFieldData(Of String)("CAVITYPAIRDSTATUS")
If (cavityPairAStatus Or cavityPairBStatus Or cavityPairCStatus Or cavityPairDStatus) = "PASS" And
(cavityPairAStatus And cavityPairBStatus And cavityPairCStatus And cavityPairDStatus) = ("PASS" Or "N/A") Then
Return True
End If
Loop
Return False
End Function
Sadly, you can't do if statements that way. You have to write the entire statement out because VB .Net does not handle string comparison that way. So a statement that would be the equivalent and work would be much longer and look like this:
If (cavityPairAStatus = "PASS" OrElse cavityPairBStatus = "PASS" OrElse
cavityPairCStatus = "PASS" OrElse cavityPairDStatus = "PASS")
And (cavityPairAStatus = "PASS" OrElse cavityPairAStatus = "N/A" AndAlso
cavityPairBStatus = "PASS" OrElse cavityPairBStatus = "N/A" AndAlso
cavityPairCStatus = "PASS" OrElse cavityPairCStatus = "N/A" AndAlso
cavityPairDStatus = "PASS" OrElse cavityPairDStatus = "N/A") Then
Return True
End If
A few more elegant solutions with creating lists are below, and can be used to help out readability some if you have to write statements like this repeatedly.
There are a couple of issues here. You can't write a If stytement in this style and you can't use binary operators (And and Or) with String.
Your If statement should be something like this:
If (cavityPairAStatus = "PASS" OrElse cavityPairBStatus = "PASS" OrElse …
If you want something a little more elegant you may consider something like this:
Dim values = {cavityPairAStatus, cavityPairBStatus, cavityPairCStatus, cavityPairDStatus}
If values.Any(Function(v) v.Equals("PASS")) AndAlso values.All(Function(v) v.Equals("PASS") OrElse v.Equals("N/A")) Then
…
End If
The way IF statement you have used is incorrect.
To compare so many conditions you need to write them separately.
Instead of using IF condition here I would suggest you to use a list.
Here's the sample code
Dim cavityPairStatus As New List(Of String)
cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRASTATUS"))
cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRBSTATUS"))
cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRCSTATUS"))
cavityPairStatus.Add(dynaset.GetFieldData(Of String)("CAVITYPAIRDSTATUS"))
If cavityPairStatus.Contains("PASS") OrElse cavityPairStatus.Contains("N/A") Then
Return True
End If

Validating multiple textboxes with multiple checks

I have multiple textboxes in a groupbox, and can successfully cycle through them all. However the checkNumbers sub fails to recognise blank/null entries, and also non-numeric characters. The correctValidation boolean should return true if all the criteria are met (no blanks/nulls, and must be a number between 1-20). Any thoughts on how to solve this would be appreciated.
Private Sub checkNumbers()
Try
For Each txt As TextBox In Me.gbTechnical.Controls.OfType(Of TextBox)()
If txt.Text <> "" And IsNumeric(txt.Text) And (Integer.Parse(txt.Text) >= 1 And Integer.Parse(txt.Text) <= 20) Then
correctValidation = True
Else
correctValidation = False
MsgBox("Please ensure all numbers are between 1 and 20")
Exit Sub
End If
Next
Catch ex As Exception
MessageBox.Show("General: Please ensure all numbers are between 1 and 20")
End Try
End Sub
I would use Integer.TryParse and then >= 1 AndAlso <= 20. You could use this LINQ query:
Dim number As Int32
Dim invalidTextBoxes =
From txt In gbTechnical.Controls.OfType(Of TextBox)()
Where Not Integer.TryParse(txt.Text, number) OrElse number < 1 OrElse number > 20
Dim correctValidation = Not invalidTextBoxes.Any()
Note that you should almost always use AndAlso instead of And and OrElse instead of Or since those operators are Is short-circuiting boolean operators. This can be more efficient and - more important - can prevent errors. Consider this:
Dim text = ""
If txt IsNot Nothing And txt.Text.Length <> 0 Then text = txt.Text
This fails if txt is nothing since the second condition is evaluated even if the first already was evaluated to false which causes a NullReferenceException at txt.Text.
if you only want a number value, why don't you try to use NumericUpDown. You can also set the Minimum and Maximum in property or use
NumericUpDown1.Maximum = 20
so, there won't be a need to do checkNumbers.
Or is there any reason that you have to use textbox??

If...Else... Statement Issue

I have the following code:
Dim UserID As String = "James"
Dim AccNo As String = "S10001"
Dim err As Boolean = False
If Left(AccNo , 1) = "S" Then
If UserID <> "Alex" Or UserID <> "James" Then
err = True
End If
End If
Why I always get the result err=True? Whats wrong with my code?
I think you maybe wanted And rather than Or, because trivially, a UserID will always not be equal to at least one of two distinctly different values, and so one or other of the comparisons will always be true:
If Left(AccNo , 1) = "S" Then
If UserID <> "Alex" And UserID <> "James" Then
err = True
End If
End If
This is because you are doing two 'not' or 'other than' statements which must always be true, because whatever value you test the other is always true.
Because while UserID is equal to 'James' it is also not equals to 'Alex' hence the condition satisfies and changes the variable to true.
That's the right result.
1st condition: Left(AccNo , 1) = "S" is true, so it enters the if block
2nd condition: (UserID <> "Alex" Or UserID <> "James") -> If either of the two result is true, you code will execute the If block.
If you don't want to enter the condition, just change the OR into AND, meaning that the User should NOT be James NOR should he be Alex
I guess you want to express something like "The user id is neither Alex nor James". This in logic would be not (UserID is Alex or UserId is James). As not (x or y) is the same as not x and not y, this equals UserID is not Alex and UserId is not James, or in VB syntax:
UserID <> "Alex" And UserID <> "James"
As a sidenote, you can make your code look a bit nicer, if you use something like this:
If Not {"A", "B", "C"}.Contains("D") Then
' do something
End If
This replaces
If "D" <> "A" AndAlso "D" <> "B" AndAlso "D" <> "C" Then
' do something
End If
Also - as you might have noticed - VB also knows "AndAlso" and "OrElse" which should in most situations used to replace "And" and "Or". Check this for an explanation: AndAlso vs And