Checking for Empty Strings
Posted
Sat, Aug 14 2010 21:46
by
Deborah Kurata
The "old school" way to check for empty strings is to use the Trim function to remove any empty spaces and then either check for a length of 0 or a string value of "".
In C#:
var str = "";
if (str.Trim().Length == 0)
{
MessageBox.Show("Please enter a value");
}
In VB:
Dim str As String = ""
If (str.Trim().Length = 0) Then
MessageBox.Show("Please enter a value")
End If
But if the string str is Null, the check above throws an exception. So to cover all of the bases, you need a null check as well.
A much easier way is to use the IsNullOrEmpty function, or new with .NET 4.0, the IsNullOrWhiteSpace.
In C#:
var str = "";
if (String.IsNullOrWhiteSpace(str))
{
MessageBox.Show("Please enter a value");
} In VB:
Dim str As String = ""
If (String.IsNullOrWhiteSpace(str)) Then
MessageBox.Show("Please enter a value")
End If
Use this technique any time you want to check whether a string has no value.
Enjoy!