Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a above code on my controller,
C#
public ActionResult Details(int? id)
{
   var dbo = new DrugBusiness();
   DrugModel dm = dbo.DetailsMethod(id);
   DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate;
   DateTime now = DateTime.Today;
   var days = drug_expdate - now;
   if(drug_expdate<=now)
   {
      ViewBag.msg = "The Drug has expired";
   }
   else
   {
      ViewBag.msg = "This Drug expires in " + days.Days + "Days";
   }
return PartialView(dbo.DetailsMethod(id));


but when im running my Details view it's giving me an error in yellow line, this what
it says "{"Object reference not set to an instance of an object."}" 

please help me ive try but nothing is working, please
Posted
Updated 26-Jul-15 22:47pm
v3
Comments
Wendelius 27-Jul-15 4:48am    
And what is the line where you get the error?
Syabonga Mthethwa 27-Jul-15 5:52am    
this is the line "DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate; "

You might notice the questionmark after int?. This means that id can also be NULL so you have to check for that.
if(id.HasValue) {
  // do something
} else {
  // id is NULL, do something else
}


Good luck!
 
Share this answer
 
Comments
Syabonga Mthethwa 27-Jul-15 6:33am    
thanks Nijboer
Probably the id you're passing cannot be found in records. Because of this, the ExpiryDate cannot be accessed. Either there is no such id or you have provided a null value for the id.

Is it intentional that you can pass a nullable into to the method. Based on the code it looks like it's not designed to handle such input.
 
Share this answer
 
Check to see if the value for "drug_expdate is not null before performing any calculations.

DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate;
DateTime now = DateTime.Today;

if (drug_expdate != null)
{
    var days = drug_expdate - now;
}
 
Share this answer
 
this is the line that is giving me error "DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate; "
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900