Search code examples
c#asp.netdatabaseasp.net-mvc-4webgrid

Object reference not set to an instance of an object - MVC 4 - WebGrid Export


I have a method for exporting a WebGrid to a .csv file but not all Surveys contain a CompanyName so I get the error 'Object reference not set to an instance of an object.'

How would I go about correcting this?

    public void DownloadCSV()
    {

        StringWriter sw = new StringWriter();

        sw.WriteLine("\"Project Number\",\"Location\"");

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Survey" + DateTime.Today.ToShortDateString() + ".csv");
        Response.ContentType = "text/csv";

        var surveys = from s in SurveyDB.Surveys select s;

        foreach (var line in surveys)
        {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                           line.projNo,
                                           line.locationName,
                                           line.Company.CompanyName
                                           ));
        }

        Response.Write(sw.ToString());

        Response.End();

    }

Solution

  • Try this:

     sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"",
        line.projNo,
        line.locationName,
        (line.Company == null || line.Company.CompanyName == null) ? "" : line.Company.CompanyName
     ));
    

    If you are using Entity Framework I suggest you update this line from:

    var surveys = from s in SurveyDB.Surveys select s;
    

    To:

    var surveys = from s in SurveyDB.Surveys.Include("Companies") select s;