我有一种将WebGrid导出到.csv文件的方法,但并非所有 Surveys 都包含 CompanyName ,因此我收到错误'未设置对象引用到一个对象的实例。'
我该怎么做才能纠正这个问题?
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();
}
答案 0 :(得分:0)
试试这个:
sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"",
line.projNo,
line.locationName,
(line.Company == null || line.Company.CompanyName == null) ? "" : line.Company.CompanyName
));
如果您使用的是Entity Framework,我建议您从以下位置更新此行:
var surveys = from s in SurveyDB.Surveys select s;
要:
var surveys = from s in SurveyDB.Surveys.Include("Companies") select s;