When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error.
The piece of code I get this error :
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check
TextBox1.Text = XResult == null ? String.empty : XResult.ToString();
If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it.
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}
That error could be Because the REquest.QueryString method did not find a value for "res" in the url so when you try to do the "toString" to a null object whrow that exeption.
Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval. It's not present in the address supplied to the browser. In the web section of your project properties, you can supply an appropriate URL. Of course, shoring up your code to allow for this would be advisable.
XResult is already a string, so calling ToString isn't necessary. That should also fix your problem.
The problem here is that XResult is null, and when you call ToString
on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check:
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}
Related
I'm basically trying to iterate over a lot of data and transform a returned data query to a more limited object within a View Model.
Rather than do a huge section of code, I'm calling .ForEach() on a list, then adding a new entry to the view model's list.
This works great, but, there is one property (Address) that is optional.
When I reach the optional item, I get NullReferenceException if the item from the DB doesn't have an entry.
A code example is:
var tmp = _context.Person.Include(x => x.Address).ToList();
tmp.ForEach(x => vm.List.Add(new IndexListItem()
{
Name = x.Name,
Address = x.Address.FirstLine + " " + x.Address.SecondLine,
ID = x.ID
}));
I have since found out from a different answer on this site that if I change the address line so that it reads:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
The code now works when I hit a null entry in tmp.
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
In addition, is the reason for me not having to do x.Address?.FirstLine? because that's a string and strings are already nullable?
A null reference exception in this particular case is caused when you are trying to access a property where the parent object is null itself.
x.Address.FirstLine
i.e. in your case Address is null.
It is not in regard to what you are trying to set (i.e. the destination view model).
The reason that this works:
x.Address?.FirstLine
..is because 'in the background' it's checking first to see if Address is null. If it isn't, then it returns FirstLine and if it is, then null is returned. It's semantically equivalent to:
if (x.Address == null)
{
return null;
}
else
{
return x.Address.FirstLine;
}
Here's a blog post about the introduction of the ?. operator in C# for some background reading: https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
You are mixing up saving data with loading data. When you save the data to the database, null is acceptable, but when you try to use the data, null is not.
The null conditional operator (?.) allows you to "shorten" an if statement, and it would be something similar to:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
string Address = "";
if (x.Address != null)
{
Address += x.Address.FirstLine;
}
// ....
Also, while not relevant to your problem, the code you are using is extremely ineffective, you are loading 2 tables to get just a few properties when you could get those properties directly from the database:
var vm = _context.Person
.Select(x => new IndexListItem
{
Name = x.Name,
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
ID = x.ID
})
.ToList();
x.Address?.FirstLine where ? is null propogation operator this means if x.Address is null set null for the FirstLine.
null propogation equivalent code
if (x.Address == null)
return null
else
return x.Address.FirstLine
All reference type variables are nullable. hence, assigning null to reference types are always valid.
string is a reference-type in your example. therefore you do not get error because string x = null is valid
Your issue isn't that Address is null and you're trying to assign it to another property that allows null, it's that you're trying to access .FirstLine in something that's null.
If Address is null, then what you're trying to do with .FirstLine is the equivalent of null.FirstLine which doesn't work. Nothing can't hold something.
The ? notation you're using that works is only effecting Address, basically saying if Address is NOT null give me the value of .FirstLine, if it is null, then give me null.
im getting null exception . while im directly exceciting this page. i want to handle null exception
C#
string json = "";
if (Request.QueryString["data"] !="")
{
json = Request.QueryString["data"];
var req = JsonConvert.DeserializeObject<Request>(json);//getting error in this line
string requestid = req.requestId;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString);
SqlCommand cmd = new SqlCommand();
connection.Open();
}
error
Value cannot be null.
Parameter name: value
Well presumably Request.QueryString["data"] is null. You're currently checking whether it's a reference to an empty string, but not whether it's a null reference. I suspect you want to use string.IsNullOrEmpty to check that:
string json = Request.QueryString["data"];
if (!string.IsNullOrEmpty(json))
{
var req = JsonConvert.DeserializeObject<Request>(json);
...
}
You can follow following two approach:-
Approach 1:
if (Request.QueryString["data"] != null && Request.QueryString["data"].toString() != string.Empty)
{
.. Your Content Goes Here
}
Approach 2:
if (!string.IsNullOrEmpty(Request.QueryString["data"].toString()))
{
.. Your Content Goes Here
}
you can u string.isNullOrwhiteSpace() Method and it returns a bool ...true if the input is empty ...false if there is any characters
You are getting such error when Request.QueryString["data"] is null. so you should check for null before using this value. in c# null cannot directly converted to String. Better method is suggested by john skeet.
string json=Request.QueryString["data"];
if(string.IsNullOrEmpty(json)){//Do your code;}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
My code is this :
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT Name FROM Table WHERE (Blogger = #Blogger)", scn);
scm.Parameters.AddWithValue("#Blogger", lblBloger.Text);
scn.Open();
MyLabel.Text = scm.ExecuteScalar().ToString();
scn.Close();
in this line :
lblLastNo.Text = scm.ExecuteScalar().ToString();
Has this error :
Object reference not set to an instance of an object.
or when I using if statement , shows same error
object Blogger= "";
if (Blogger.ToString() != string.Empty)
{
....
}
in below code again shows same error .
Most likely scm.ExecuteScalar() is bringing you a null value. You need to test the value returned before using it:
var result = scm.ExecuteScalar();
MyLabel.Text = result == null ? '' : result.ToString();
scm.ExecuteScalar() is returning null, or scm is null, or lblLastNo is null. That's the only reason you get the error 'Object reference not set ..'.
ExecuteScalar return an Object type. This is why you have the same behavior on scm.ExecuteScalar().ToString(); or Blogger.ToString().
The object type default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.
If this object is NULL, you will receive the error Object reference not set to an instance of an object.
Your second case with :
object blogger= "";
if (blogger.ToString() != string.Empty)
{
....
}
Should not throw an Exception but return a string that represents the object instance. For example : "YourNameSpace.Blogger"
Please enclose with try catch block, so that you can handle runtime exceptions and its makes life easier to understand the problem. and for if (Blogger.ToString() != string.Empty) this u can check for Null condition or if its string. Then you can check for String.IsNullorEmpty
string str=blogger.toString();
if (String.IsNullOrEmpty(str))
//do something
else
//do other part
String Is Null or EMpty
I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.
If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?
DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");
//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.
user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.
I.e.
var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value; // Will return null and not error
You need to check the value itself, the best way through the null coalescing operator:
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? "Not found").ToString();
Store the contents of usr.Properties["telephoneNumber"]; in a variable and check for null:
PropertyValueCollection tel = usr.Properties["telephoneNumber"];
textBoxFirstName.Text = (tel != null && tel.Value != null)
? tel.Value.ToString()
: "";
Use the null-coalescing operator (??) operator.
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? String.Empty).ToString();
This way the value is replaced with an empty string if null. You could also just return null instead of String.Empty, the reason your code is crashing is because you're trying to call ToString() on a null value.
Something like this should work. If telephoneNumber is not null, it will convert the value to a string, otherwise it will use an empty string.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null
? usr.Properties["telephoneNumber"].Value.ToString()
: "";
A couple of things will help this be more graceful:
Test usr.Properties["telephoneNumber"] for null before calling child properties like Value. I haven't worked with AD myself, but most string-keyed indexers are designed to gracefully handle non-existent keys. the CLR, on the other hand, will happily throw a NullReferenceException any time you try to reference a member of anything that evaluates to null.
On the off chance that AD DOES blow up on a nonexistent column, enclose the assignment in a Try-Catch block that will show an error on the screen and gracefully continue processing (or not).
Use this code
SearchResult.Properties.Contains("property")
To check if the object actually has the prop loaded from the search result
if (usr.Properties["telephoneNumber"] != null)
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
I have the following line of code:
var selectedDomainID = lkuDomainType.EditValue.Equals(null)
? string.Empty
: lkuDomainType.EditValue;
Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?
Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.
When you use Object.Property and Object is undefined, you are dereferencing a null pointer and that's why you get the exception. Instead, use:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If EditValue is null then you can't call Equals. In this cas you would have to do:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
Or you can simplify it by doing:
var selectedDomainID = lkuDomainType.EditValue ?? string.Empty;
you are trying to call the Equals method on a null object - do it like this instead:
lkuDomainType.EditValue == null
The problem is that you are using the object before checking if it's null. You are calling the Equals method of the object, which fails if the reference is null.
You have to exchange your lkuDomainType.EditValue.Equals(null) for lkuDomainType.EditValue == null.
EditValue == null. That means that there is no object there. You cannot call functions on null objects, even if the function is .Equals().
You're better off just saying "(lkuDomainType.EditValue == null)" in this case.
You should use String.IsNullOrEmpty here. Like this:
var selectedDomainID = String.IsNullOrEmpty(lkuDomainType.EditValue) ? string.Empty : lkuDomainType.EditValue;
Equals is a method, you're trying to call a method on a null object which is throwing an exception.
when EditValue is null you cannot call the Equals method on it so the best way to check is to use
lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If lkuDomainType.EditValue is null, then "lkuDomainType.EditValue.Equals(someObject)" is the same as coding "null.Equals(someObject)". Well, obviously "null" doesn't have any members or methods (it wouldn't be null if it did). That's why you get a NullReferenceException.
Most of the examples from the other posts will work, including String.IsNullOrEmpty, which is a method that returns a boolean value.
All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.
Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.
Consider the following code:
int? num = null; // int? is Nullable<int>
String s = null; // String is a class
var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null); // throws
The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.
As other people said, the way to go in the OP's case is to use == or ??.