Object reference not set to an instance of an object.
This question already has an answer here:
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0 as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch (or any variable for that matter) is not null before you dereference it using the dot character ( . ) - ie before you do strSearch.SomeMethod() or strSearch.SomeProperty you need to check that strSearch != null .
In your example you want to make sure your string has a value, which means you want to ensure the string:
String.Empty / "" ) In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null .
All versions of .Net:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
.Net 4.0 or later:
if (String.IsNullOrWhitespace(strSearch))
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
链接地址: http://www.djcxy.com/p/28034.html上一篇: 如何解决未将对象引用设置为对象的实例?
下一篇: 你调用的对象是空的。
