Can someone help me to write a code that checks if string is empty and returns null if its true?
I have this now:
If(Not IsNothing(role.ROLE_DESC),role.ROLE_DESC.ToString(),Nothing)
But it only checks if role_desc is null, but I need to also check if its value is not an empty string and if so, then return null.
What taquion said, or IsNullOrWhiteSpace.
Looks like:
If TypeOf role.ROLE_DESC Is String AndAlso String.IsNullOrEmpty(role.ROLE_DESC) OrElse String.IsNullOrWhiteSpace(role.ROLE_DESC) Then
'It is empty or whitespace
Else
'it isn't empty or whitespace
End If
Related
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 "").
What is wrong with my If condition?
If Not IsEmpty(Wrkgps_L3) And Not IsEmpty(Wrkgps_L4) Then
Wrkgps_L3L4 = Wrkgps_L3 & "," & Wrkgps_L4
End If
The Not condition doesn't seem to work. The code within the If statement gets executed even when both Wrkgps_L3 and Wrkgps_L4 are empty strings.
Update:
Wrkgps_L3 and Wrkgps_L4 are variables that contain results returned from a function. I noticed that IsEmpty(Wrkgps_L3) = False even though Wrkgps_L3 = "". I had to rewrite my code to
If (Wrkgps_L3 <> "") And (Wrkgps_L4 <> "") Then
In any case, I am still intrigued to know why IsEmpty doesn't work on variables with ""?
In Visual Basic, Empty and "" (an empty string) are two different things. Empty is the uninitialized state of a Variant variable, and IsEmpty tests whether a Variant variable has the Empty value:
Dim x As Variant
If IsEmpty(x) Then
Debug.Print "x is empty"
End If
As you've observed, you must compare against "" when checking whether a String variable contains an empty string.
If the variables are strings, you could also:
If Len(Wrkgps_L3) + Len(Wrkgps_L4) = 0 Then
' They're both empty string variables
Else
' One or the other contains at least one character
End If
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.
What are NULL values ?
Sometimes when I try to assign a query to variable, I get error saying Type-Cast-Error.
txtMiddleName.Text = Reader.GetString(2)
How can I put it that if the value of the Middle is nothing then
txtMiddleName.Text = ""
(I already read the other post "Handling NULL Values in SQLite but couldn't figure out much")
Working on VS 2010 (VB.net)
EDIT 1:
This is the error Message I get
(Line 364 is the above mentioned code)
NULL means there is no assigned value to the field.
The blank value in the MiddleName in the third row of your table is an empty string not a NULL.
If your are expecting a NULL to be a value of an object you can check it before assign it to another.
In your example you have to check for DBNULL values like the following:
if (Reader.IsDBNull(2))
{
// Do something ..
}
else
{
// Do something else ..
}
If you are not sure of the type of the value you are trying to get, use the following:
Reader.GetValue(2).ToString()
I think you should check
if(dread[2] != DBNull)
//assign value
The error is occurring as its trying to transform the database null value to string
Check for null before assigning the value to the textbox
If(Not Reader.IsDBNull(2)) Then
txtMiddleName.Text = Reader.GetString(2)
End If
there a constant called DBNull.value that you can use in comparisons to determine if it is a null or an empty string, a string like "". If you use a strongly typed data adapter you can also use datatable.IsMiddleNameNull() function to see if it is null.
Simple recap:
"" != null
and
null != DBNull
To actually answer your question, you are probably getting a DBnull value when you are getting the string from the reader. So before calling getString you need to make sure the value is not DBNull.value and then call getstring.
Try this out. May this will help you.
Dim a As string
a = TextBox1.Text
If String.IsNullOrEmpty(TextBox1.Text) Then
MessageBox.Show("Please enter Your Middle name")
Else
MessageBox.Show("your Middle name is " & a)
End If
I like to confirm that array is created, how can it be done? There is no nul keyword?
Dim items As Array = str.Split("|")
if (items=null) then ???
To check if an object is null in VB.Net you need to use the Nothing keyword. e.g.
If (items is Nothing) Then
'do stuff
End If
However string.Split() never returns null, so you should check the input string for null rather than the items array. Your code could be changed to something like:
If Not String.IsNullOrEmpty(str) Then
Dim items As Array = str.Split("|")
'do stuff
End If
Try using String.IsNullOrEmpty on your string variable before splitting it. If you attempt to split the variable with nothing in the string the array will still have one item in it (an empty string), therefore your IsNothing checks on the array will return false.
String.Split can never return null. At worst, it can return an array with no elements.
Use "Is Nothing" to test for Null in VB.NET.
If items Is Nothing Then
End If
The keyword for null in VB is Nothing.
However, this is not what you want to use in this case. The Split method never returns a null reference. It always returns a string array that has at least one item. If the string that you split was empty, you get an array containing one string with the length zero.
So, to check if you get that as result you would do:
Dim items As String() = str.Split("|")
If items.Length = 1 and items(0).Length = 0 Then ...
It's of course easier to check the input first:
If str.Length = 0 Then ...
For a one liner do this:
destinationVariable = if(myvar is nothing, "", myvar)