This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a page.aspx that reads the query string, and if the QueryString is something like page.aspx?id=1, it runs some code.
However, I want it to simply ignore that code if no QueryString is specified. If I simply go to page.aspx. Right now, the only code I have on page load is
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
That works if I go to page.aspx?id=1. However, simply going to page.aspx gives me this error:
object reference not set to an instance of an object
How can I load the page with no query string?
You need to check for nulls
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
You can do this:
if(Request.QueryString.Length != 0)
{
...
}
If you try to access elements which are not present, you'll receive an exception. So, since QueryString has a property of Length, checking it against 0 means there is no query string at all.
Else if you want to know that only if id key isn't present, you can do this:
if(Request.QueryString.AllKeys.Contains("id"))
{
}
Try this:
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
Another way :
string id = Request.QueryString["id"] ?? "";
if(id == "1")
{
//Do something
}
This will cover any null reference issues or when there simply is an empty query string
if (Request.QueryString != null && Request.QueryString["id"] != null && Request.QueryString["id"] == "1")
{
//do work
}
Whenever you see this error :
object reference not set to an instance of an object
Know that you are checking for something that is null or simply doesn't exist
so try this :
if(Request.QueryString["id"] != null)
{
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
}
Related
I have a asp.net app where I utilize hidden fields to store values (if need be).
So on the designer side I have this..
<asp:HiddenField ID="hdDDAPDischargeDate" runat="server" />
In my C# code I either assign a value to it or leave it as is, so basically something along the lines...
if ( condition.........)
{
hdDDAPDischargeDate.Value.ToString()== '10/23/2017'
}
But in many cases I don't assign a value, so later on when i go to check what the value of it is, i can't get it to hit the ELSE part of the if statement
I tried:
if (hdDDAPDischargeDate.Value != null)
if (hdDDAPDischargeDate.Value.ToString != null)
But in both cases it thinks there's a value in the field, or I'm basically checking it wrong
If i hover over the field, it simply shows ""
Hidden fields can't be null, which makes sense if you think about the way they are represented in the HTTP request.
Try checking for an empty string instead:
if (hdDDAPAdmissionDate.Value != "")
{
//Foo
}
If for some reason you don't believe me or are not sure, you can always check both:
if (hdDDAPAdmissionDate.Value != null && hdDDAPAdmissionDate.Value != "")
{
//Foo
}
Or better yet:
if (!string.IsNullOrEmpty(hdDDAPAdmissionDate.Value))
{
//Foo
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have the following method:
void setTexts()
{
if (queueIn != null)
{
queueIn.text = countIn.ToString();
}
if (queueOut != null)
{
queueOut.text = waitingForPickup.ToString();
}
}
I want it to do nothing if queueIn is null, but I keep getting a null reference exception saying queueIn is null. Why is it going into the if block when queueIn is null?
EDIT: the problem disappeared when I added a Debug.Log check, so it probably hadn't saved the previous dozen times or something. Thanks for your suggestions! I'm pretty new to C#.
You need to check all object deference points. In this case, countIn could be your offender.
Here's a possible solution to remove your exception.
void setTexts(){
if (queueIn != null && countIn != null) {
queueIn.text = countIn.ToString ();
}
if (queueOut != null && waitingForPickup != null){
queueOut.text = waitingForPickup.ToString();
}
}
You are calling ToString() on countIn and waitingForPickup - you need to check them too. E.g.:
void setTexts(){
if (queueIn != null && countIn != null) {
queueIn.text = countIn.ToString();
}
if (queueOut != null && waitingForPickup != null) {
queueOut.text = waitingForPickup.ToString();
}
}
So I have a Retrieve() function, which either gets me an object or a null (if that object is not found). I'm using an if statement with a boolean attribute of that object. It's set up like this.
if(Retrieve(index).IsForm == true) {}
The issue with this is that if it doesn't find an object, it'll throw a null reference exception. There are some ways around this, of course, but none that I find concise. There's a try...catch, but that seems pointless when I expect the error. I can check if the object is null first, if(Retrieve(index) != null), but that seems like adding needless nesting. Is there a clever way to handle this? I thought of using the null coalescing operator but it doesn't work in this situation.
You can either call the method twice:
if(Retrieve(index) != null && Retrieve(index).IsForm == true) { }
Or you can break the lines apart and store the result before the if:
var result = Retrieve(index);
if(result != null && result.IsForm == true) { }
You could write an IsForm function to do both operations for you:
bool IsForm(int index)
{
var result = Retrieve(index);
return result != null && result.IsForm;
}
if (IsForm(index))
...
The Null Object pattern would be helpful here. It keeps your calling code clean but does add an additional class.
class NullWhatever : Whatever
{
public NullWhatever() { IsForm = false; }
}
Whatever Retrieve(...)
{
...
return new NullWhatever(); // instead of null
}
You could make a Nullable_IsForm extension method. Then you could check for the null condition.
public static class RetrieveExtension
{
public static bool? Nullable_IsForm(this Retrieve retrieved)
{
if(retrieved == null)
{
return null;
}
else
{
return retrieved.IsForm;
}
}
}
Then in your code you'd check it against bool values
if(Retrieve(index).Nullable_IsForm == true)
{}
else if (Retrieve(index).Nullable_IsForm == false)
{}
else if (Retrieve(index).Nullable_IsForm == null )
{}
I don't think there is any more concise way to do it, no.
Shortest I can think of is:
if(Retrieve(index)!=null && Retrieve(index).IsForm == true) {}
but I don't like this because it calls Retrieve(index) multiple times. I'd go for
var foo = Retrieve(index);
if(foo!=null && foo.IsForm == true) {}
but that is obviously not doing anything clever or more concise. It is probably more efficeint than some of the alternatives.
You could put both conditions in the same if:
if(Retrieve(index)!= null && Retrieve(index).IsForm == true) {}
Thanks to short-circuit, if the null-check fails, rest of the expression is not evaluated.
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 want to check that session is null or empty i.e. some thing like this:
if(Session["emp_num"] != null)
{
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
}
Or just
if(Session["emp_num"] != null)
{
// The code
}
because sometimes when i check only with:
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
I face the following exception:
Null Reference exception
Use this if the session variable emp_num will store a string:
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//The code
}
If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
if at all above fails.
You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.
I'd go with your first example - but you could make it slightly more "elegant".
There are a couple of ways, but the ones that springs to mind are:
if (Session["emp_num"] is string)
{
}
or
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}
This will return null if the variable doesn't exist or isn't a string.
You should first check if Session["emp_num"] exists in the session.
You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])
If It is simple Session you can apply NULL Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}
Check if the session is empty or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty or not in C# MVC Version Above 5.
if(Session["emp_num"] != null)
{
//cast it and use it
//business logic
}