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
}
Related
I am using MVC with Razor views. In this particular view, I am passing a single instance of the class Bed. Bed has a property string Infection. Now in this instance, I have a boolean HasInfection defined in the view that I am using elsewhere to change what is displayed. This was originally declared as
var HasInfection = (Model.Infection.Trim() != "";
and worked as expected. However, there is now a use case where Bed may be null. Here is that first block of code:
#{
ViewBag.Title = "Edit";
var HasInfection = false;
if (Model != null)
{
HasInfection = Model.Infection.Trim() != "";
} // I get a NRE on this line whenever Model is null
}
I have even tried the convoluted nested if-else solution, and I still get an NRE on the closing brace of if.
if (Model.Infection == null)
{
HasInfection = false;
}
else
{
if (Model.Infection != "")
{
HasInfection = true;
}
else
{
HasInfection = false;
}
}
I've tried every combination of &/&&/|/|| I can think of with no success. If Model is null or Model.Infection == "", HasInfection should be false.
What am I doing wrong?
EDIT
After attempting var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection); (since Infection could be " "), I still get a NullReferenceException. Is it possible the issue is in the Controller even if the exception is in the View?
public ActionResult EditReservation(int Facility, string Room, string Bed)
{
var BedModel = New Bed();
List<Bed> _b = BedModel.GetBed(Facility, Room, Bed);
Bed result = _b.Where(bed => bed.BedStatus == "R" || bed.BedStatus == "A").FirstOrDefault();
return View("Edit", result);
}
I had the same problem.
When looking to the second comment in this question I found out my exception was actually 35 lines further down the road (outside the brackets) than the closing bracket where the NullReferenceException pointed to.
For ex:
if(Model.Infection != null)
{
<p>Some Html</p>
} //given NullReferenceException location
<p>Model.Infection</p> //Actual cause of NullReferenceException since
//here Model.Infection can be null
You should be able to do something like this:
var HasInfection = Model != null && !String.IsNullOrWhitespace(Model.Infection)
I can't think I've ever passed a null model to a Razor view, but I can't see why this wouldn't work.
As an aside, you could consider having a 'NullBed' object you could pass, which behaved in whatever way you deemed right for a 'missing' bed object - then you wouldn't need to be checking for nulls all over the place, which can become a pretty wearisome tyranny.
Edit: Now you've posted the controller code, it doesn't appear that Model can ever be null anyway, so this seems like a distraction. I suspect you're looking in the wrong place for whatever the problem is.
Edit2: Oh, now it's gone again from the controller code. Feels like a bit of systematic use of the debugger might be more effective than StackOverflow... I would start by passing something fixed, and known into the View call in the controller and then working out what's going on, perhaps by displaying things in your view.
If you're in control of the Bed class, you could help yourself and your successors by adding a HasInfection property to the Bed, which does whatever it needs to to return that boolean. You could similarly improve the controller by moving that BedStatus check into a property. The benefit of this would not merely be stylistic, it would help debug this sort of problem, because stuff relating to the bed object would be happening in that code, and the only stuff left in the view (a horrible place to be debugging) would be much simpler.
HasInfection = Model != null && !string.IsNullOrWhitespace(Model.Infection);
first check Model is null or not if Model is not null then check Model.Infection is Empty or not
Try this:
if(Model != null && Model.Infection != null && Model.Infection.Trim() != "")
{
HasInfection = true;
}
Hopefully this is an easy one. Is there a way to test for an "empty" field using DataRow? The following work fine for testing against a field with null values, unfortunately, the column I'm dealing with are either populated with data or are just "empty". Is there an approach in C# I'm missing? Thanks
if (Particle.Tables.Count == 0 || pDr.ItemArray[1].ToString() == "")
tblParticle.Append("No Data");
you can use stirng.isNullorEmpty to check for empty fields. String.isNullorEmpty
if (Particle.Tables.Count == 0 || string.isNullorEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
.
if (string.IsNullOrEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
else
{
//else do something else
}
checking for NULL will not hurt keep in mind that Null and Empty are two different things
See DataRow.IsNull method - it accepts a column name or index
and returns whether it is NULL
The following assumes we are talking about a string (VARCHAR/CHAR) column:
If you don't care if it is null or an empty string, and always want an empty string back, you can use DataRow["name"].ToString()
If you want your string object to become null or empty just like the field value, you can use DataRow["name"] as string
If you want to get an exception in case of NULL, you can use (string) DataRow["name"]
I have an object model somewhat like this:
public class MyObject
{
public string String1 { get; set; }
public string String2 { get; set; }
...
}
When the object initializes, all the string values are set to null.
Later on, I'm writing a method that evaluates the value of these strings to prepare an update in the DB. Something like this:
if (TheObject.String1 != null) { TheObjectInDB.String1 = TheObject.String1; }
if (TheObject.String2 != null) { TheObjectInDB.String2 = TheObject.String1; }
TheObject is an instance of MyObject and TheObjectInDB is an instance of the linq-to-sql map for the table I'm updating.
My question is this: is using the null a safe way to do it or could it cause problems later? Should I create a constructor that initializes these strings to "" and in the update check if the strings are = "" instead of = null?
Thanks for the advice.
There is nothing more, or less safe about null or an empty string. It is entirely your choice. Because both are often used to indicate the abscence of data or information, there is a convenience method string.IsNullOrEmpty that allows you to accept either value.
In your case, I would stick with the easiest option, null.
You could initialize both properties to string.Empty (preferred to "") and then check for string.Empty when setting the properties, however only if you can guarantee that either:-
a) the value being set is never string.Empty
or
b) the value being set is string.Empty but the values are only set once
I'd stick with checking for null to avoid either of the above causing potential issues in the future.
There is no problem here, the code you are using should work without any problems.
I can't even think of 'problems that this can cause 'later''.
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
}
So, First of all. Code:
I've got a class:
public class Myobject
{
public string Code { get; set; }
public DateTime? StartDate { get; set; }
}
And this is part of very simple source:
MyObject mo = new MyObject();
mo.Code= "sth";
// NO action on StartDate property!
if (mo.StartDate.HasValue)
{
sc.Parameters.Add(new SqlParameter("#inStartDate", mo.StartDate.Value));
}
else
{
sc.Parameters.Add(new SqlParameter("#inStartDate", DBNull.Value));
}
Simple 'if' - Sql Server 2008, throw an error - when gets null Datetime (it has to be DBNull.Value)
So I want to check it first, and then pass right value or DBNull.
My problem is - this 'if' always retruns true! Why!?
Also tried that:
if (mo.StartDate.Value == null)
but it always returns false. How come it is not a null? It was not even created..
So.. How to check if DateTime object was not assigned?
Try this:
if (mo.StartDate.GetValueOrDefault() != DateTime.MinValue)
{
// True - mo.StartDate has value
}
else
{
// False - mo.StartDate doesn't have value
}
should just be able to do
mo.StartDate != null
instead of
mo.StartDate.Value != null
Running the simplest test with that class (as you presented it) yields false:
var mo = new Myobject();
Console.WriteLine(mo.StartDate.HasValue);
Output is False.
I'd put a breakpoint on your constructor (if you have one), make sure nothing else is getting assigned, and walk through any methods called along the way to make sure there's nothing else setting the property that may not be immediately obvious...
Can you post more code, perhaps? There must be something in code not posted setting the property.
.HasValue and ==null are the ways to check whether DateTime? is assigned a value or not. You are doing it right. There might be problem somewhere else that .HasValue returns true always.
The way you're checking for null is fine, there must be something else that's setting the field's value.
To find what's setting the field you could right-click it then do find all references, then scan the list for any assignments.
Failing that, you could change it to an explicitly defined property temporarily and set a breakpoint within the set method, then execution will pause whenever the value is set and you can look up the call stack.