VB.NET - If string contains "value1" or "value2" - vb.net

I'm wondering how I can check if a string contains either "value1" or "value2"?
I tried this:
If strMyString.Contains("Something") Then
End if
This works, but this doesn't:
If strMyString.Contains("Something") or ("Something2") Then
End if
This gives me the error that conversion from string to Long can't be done.
If I put the or ("Something2") inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.
So how can I check if the string contains either "string1" or "string2" without having to write too much code?

You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if

You need this
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
'Code
End if

In addition to the answers already given it will be quicker if you use OrElse instead of Or because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
If strMyString.Contains("Most Likely To Find") OrElse strMyString.Contains("Less Likely to Find") Then
'Code
End if

Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.

You have ("Something2") by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.

If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if

I've approached this in a different way. I've created a function which simply returns true or false..
Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function

If you want to disregard whether the text is uppercase or lowercase, use this:
If strMyString.ToUpper.Contains("TEXT1") OrElse strMyString.ToUpper.Contains("TEXT2") Then
'Something
End if

Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.
If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.

Related

Excel Vba-Similar Function

I'm so confused in resolving this:
In VBA syntax there is this function:
If Left("abcdef",3)="abc" then
Msgbox "True"
This function is too simple but is there any way for e.g.
To have something like this
If left("abcdef",3) is in ["A".."Z"] or if left("1265avd0",2) is in [1..9]
Which mean checking if left ("abcdef",3) which is equal to "abc" is in this Interval ["A".."Z"] or checking if the left("123avd0",2) is numeric and is in the interval of [1..9]
Hope you are understading what I want to do
Can anyone Light me in doing This?
You can use the Like operator for this simple type of comparison.
Option Explicit
Option Compare Text 'for case insensitive matching
Sub dural()
Const S1 As String = "abcdef"
Const S2 As String = "1265avd0"
Debug.Print Left(S1, 3) Like "[A-Z][A-Z][A-Z]"
Debug.Print Left(S2, 2) Like "[1-9][1-9]"
End Sub
Both will return TRUE in this instance.
As pointed out by #chrisneilsen, the comparisons can be simplified to:
S1 Like "[A-Z][A-Z][A-Z]*"
S2 Like "[1-9][1-9]*"
And you can test for either with something like:
If Left(myString, 3) Like "[A-Z][A-Z][A-Z]" or _
Left(myString, 2) Like "[1-9][1-9]" then
'do something
End if
And in the simplified version:
If myString Like "[A-Z][A-Z][A-Z]*" or _
myString Like "[1-9][1-9]*" then
'do something
End if
More complex pattern matching can be done using Regular Expressions.
If you prefer to not set Option Compare then change the alpha patterns to "[A-Za-z]"
You can use Regular Expressions ("RegEx") for this.
The pattern has a non-capturing group (?:...) that can determine if the start of the string ^ contains either three letters of any case: [a-zA-Z]{3} or | two digits \d{2}.
If either criterion is met, then the MsgBox will return True, otherwise, it returns False.
Sub test()
Dim RegEx As New RegExp, testString As String
testString = "53bcko390872"
With RegEx
.Pattern = "^(?:[a-zA-Z]{3}|\d{2})"
MsgBox .test(testString) 'will prompt True/False
End With
End Sub
You can replace the MsgBox line with something useful, such as
If .test(testString) [= True] Then...
Click Here for a live demo on the regex working (optional).
Note that you will need to set a reference to Microsoft VBScript Regular Expressions x.x

Visual Basic .NET Empty/Null String difference?

I would like to differentiate between NULL and "".
How do I determine with an if statement if a String is NULL or ""?
Nothing is when the string variable has no instance it refers to at all while "" is when the string variable has something it refers to and it is an empty string.
To distinguish, you could put the following conditions:
Dim s As String
If s Is Nothing Then 'It means it is Nothing
End If
If s = "" Then 'It means it points to some instance whose value is empty string
End If
VB.Net also has String.Empty which is equivalent to "":
If s = String.Empty Then
End If
"" is just an empty string, but it is still initialized and has an allocated position in the memory as a string with no characters.
Null or Nothing is a string that has not been initialized or defined, which means that there is no memory is allocated for this, thus the string technically doesn't exist.
To check if a string is null you'd do:
If str Is Nothing Then
To check if a string is empty you could do:
If str = "" Then
or:
If str.Length = 0 Then
However, to check if it's either null or empty, you get use of the String.IsNullOrEmpty() method:
If String.IsNullOrEmpty(str) Then
you can get dbnulll error if string come from database
you can determine it with
isdbnull(str)
Pass your string variable into this function to test for both:
String.IsNullOrEmpty(s)
You can test for null like this:
s Is Nothing
You can test if it is an empty string like this:
s = String.Empty
The accepted answer and the others are all partially wrong because they do not address a crucial point of empty strings in VB. According to the documentation:
For strings in Visual Basic, the empty string equals Nothing. Therefore, "" = Nothing is true.
This means that MyString = String.Empty will be true when MyString Is Nothing is also true. So you definitely want to test against Nothing before testing against String.Empty (or "").

Assign Nothing to a Short variable in VB.NET

I have a below line of code like this.
Private Sub SomeFunction(ByRef SomeShortVariable As Nullable(Of Short))
Dim SomeStringVariable As String = "" 'Let's assume it is "", that's how I am getting it in real time code
SomeShortVariable = IIf(SomeStringVariable = "", Nothing, SomeStringVariable) 'I want to set SomeShortVariable to Nothing but I am getting 0
End Sub
The variable SomeShortVariable is always sets to 0 even though I want it to be Nothing.
I know Short by default will set the variable to 0.
But how can I make it Nothing. I am using .NET 2.0.
Make SomeShortVariable a Nullable(Of Short) variable.
EDIT:
Also your statement should look like this:
SomeShortVariable = If(String.IsNullOrEmpty(SomeStringVariable), Nothing, New Nullable(Of Short)(Short.Parse(SomeStringVariable)))
SECOND EDIT:
If you're using Visual Studio 2005 the above won't work, because the If operator was only introduced in VS2008. So what you'll have to do is this:
If String.IsNullOrEmpty(SomeStringVariable) Then
SomeShortVariable = Nothing
Else
SomeShortVariable = Short.Parse(SomeStringVariable)
End If
Of course you will want to validate that SomeStringVariable is a numeric string first. :)
Regarding your update, well, that's cause it's Short, and not Nullable(Of Short) in the parameter. Make it nullable of Short and you are done. Although I would refactor to avoid ByRef, have a string parameter SomeStringVariable and return a Nullable(Of Short). Then things would start to make more sense.
Private Shared Function SomeFunction(SomeStringVariable As String) _
As Nullable(Of Short)
If String.IsNullOrEmpty(SomeStringVariable) Then
Return Nothing
Else
Return Convert.ToInt16(SomeStringVariable)
End If
End Function
EDIT: Actually shorthand syntax won't work in this case, for the reasons I outlined in my comment regarding change to If. Just don't use shorthand.
Watch out for the recommendations to use Convert or Parse on cases where the input string could be something other than an empty string but not a number (any user supplied input). It is typically better to use TryParse unless you are absolutely sure someone hasn't passed something in that you aren't expecting. Consider the following:
Dim someString = "a"
Dim someShort as new Nullable(Of Short)
Dim tempShort as Short
Console.WriteLine(someShort)
If Integer.TryParse(someString, tempShort) then
someShort = tempShort
end if
console.WriteLine(someShort)
if Not String.IsNullOrEmpty(someString) then
someShort = Short.Parse(someString) ' Throws FormatException
end if
Console.WriteLine(someShort)

String.Contains Function in Visual Basic 2008 or 2012

How do I find a unique string that contains in a single .txt file with different strings in each line?
Example:
The .txt file contains the following
012345
023456
034567
045678
056789
Then I want to find one of the set of numbers.
This is what I want to happen~
Dim stN As String = TextBox1.Text
If stN.contains(.txt file) Then
'Anything to do here
Else
MsgBox("Your input number is incorrect", "ERROR")
End If
I assume your pseudo code should be the other way around: If .txt-file.Contains(stN) Then.
So you want to know if a string equals one line of a text-file:
Dim lines = File.ReadLines(path)
Dim fileContainsLine = lines.Any(Function(l) l.Trim.Equals(TextBox1.Text, StringComparison.OrdinalIgnoreCase))
If you don't want to compare case-insensitively use l==TextBox1.Text instead. If the Trim is also unnecessary you could simplify it to:
Dim fileContainsLine = lines.Contains(TextBox1.Text)
Here is a little Linqpad program, but you would probably want to read in the file one time and cache it.
Sub Main
If (CheckContains("023456")) Then
Console.WriteLine("True")
Else
Console.WriteLine("False")
End If
End Sub
Function CheckContains(inputVal as String) as Boolean
Dim query = From line In File.ReadAllLines("C:\code\so\sample.txt") _
Select line
return query.Contains(inputVal)
End Function

Passing a string to a database with ToUpper? VB.NET 2010

I'm trying to validate a textbox. If user enters all lower case characters then convert it to all upper case. So when its added to the database its all upper case. I need help with my function, I don't know if its a syntax error or something, here it is. I'm using VB.Net 2010
Public Function CheckLetters(ByVal strIn As String) As Boolean
Dim i As Integer
Dim strOne As String
For i = 0 To Len(strIn) - 1
strOne = strIn.Substring(i, 1).ToUpper
Select Case strOne
Case "A" To "Z"
Case Else
Return False
End Select
Next
Return True
End Function
How 'bout this:
Return Regex.IsMatch(strIn, "^[a-z]*$")
or this
Return strIn.All(Function(c) Char.IsLower(c))
There's no good reason for this method to be anything other than a one-liner. But if you really want to loop through the characters:
For Each c As Char In strIn
If Not Char.IsLower(c) Then Return False
Next c
Return True
Your code runs just fine here (VB does not require the brackets after ToUpper, but it's good for readability) - it accepts a string and returns True if that string only contains the characters "A" through "Z", false otherwise. The function doesn't convert anything - just returns that Boolean result.
If you want to actually convert the string to upper case, just use .ToUpper() on the string itself, e.g.
Dim MyString As String = "Contains some text"
MyString = MyString.ToUpper()
' Above would set MyString to "CONTAINS SOME TEXT"