Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, I'm currently working on an MVC 5 project with c#.

I'm trying to create a List of the ApplicationUsers to find the customer that corresponds to the correct Invoice. I tried the following below, but got a NullReferenceException:

System.NullReferenceException: Object reference not set to an instance of an object.

The code in my Controller:

C#
private string FindCustomerForReservation(List<Invoice> invoices, List<ApplicationUser> customers, Reservation currentReservation) 
{ 
    string customername; Invoice correspInvoice = invoices.Find(f => f.Id == currentReservation.Invoicenumber); 
    ApplicationUser customer =  customers.Find(k => k.Id == correspInvoice.CustomerId);   
       
    customername = customer.UserName; return customername; 
}


"customer" seems to be empty but I don't know why.

How would I fix this?

What I have tried:

I've tried to look in debugging mode, but I still can't figure out why customer stays empty.
Posted
Updated 20-Mar-19 16:14pm
Comments
Bryian Tan 20-Mar-19 22:42pm    
did you check what in the correspInvoice ?

If customers is null, it's because your view code isn't passing anything back to the controller to fill in the customers variable.

It's impossible to tell you why that is from what you posted.
 
Share this answer
 
You just need to add a null check

if( customers != null && customers.Count > 0){
   //do the query here
}
 
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