Articles in this section
Category / Section

How to handle null exception when exporting grid with foreign key columns in .NET WebForms application?

1 min read

Problem

When we export the grid with foreign key columns, the dataSource type of the foreign key columns is passed as generic object to the export function. As we don’t have support to export generic type list, a null exception is thrown like mentioned below.

<Exception>

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=Syncfusion.EJ.Export
  StackTrace:
       at Syncfusion.EJ.Export.GridExcelExport.ProcessRecordCell(Object row, Column column)
       at Syncfusion.EJ.Export.GridExcelExport.<>c__DisplayClasse.<ProcessRecordRow>b__d(Column column)
       at System.Collections.Generic.List`1.ForEach(Action`1 action)
       at Syncfusion.EJ.Export.GridExcelExport.ProcessRecordRow(Object row)
       at Syncfusion.EJ.Export.GridExcelExport.RenderRecord()
       at Syncfusion.EJ.Export.GridExcelExport.ProcessGridContents()
       at Syncfusion.EJ.Export.GridExcelExport.IterateElements()
       at Syncfusion.EJ.Export.GridExcelExport.ExportHandler()
       at Syncfusion.EJ.Export.GridExcelExport.ExecuteResult(GridProperties GridModel, IEnumerable dataSource)
       at Syncfusion.EJ.Export.GridExcelExport.Export(GridProperties gridModel, IEnumerable dataSource, Boolean multipleExport)
       at Syncfusion.EJ.Export.ExcelExport.Export(GridProperties gridmaodel, IEnumerable datasource, String excelname, ExcelVersion excelversion, Boolean isHideColumnIncude, Boolean isTemplateColumnIclude, String theme)
       at EMIMReports._Default.dgReport_OnServerExcelExporting(Object sender, GridEventArgs e) in C:\Visual Studio Projects\2014\ESJS\EMIMReports\EMIMReports\Default.aspx.vb:line 99
       at Syncfusion.JavaScript.Web.Grid.PostBackEventHandler(String EventName, Dictionary`2 args)
       at Syncfusion.JavaScript.Web.CommonDataBoundControl.RaisePostBackEvent(String EventArgument)
  InnerException:

</Exception>

Reason

Since we have deserialized the grid model obtained from the client side (where the column dataSource is a generic JSON object), it is deserialized to generic list

Solution

In order to overcome this issue, we need to dynamically set the dataSource for the foreign key columns before calling the Export method as explained in the below example.

Grid Rendering Code.

@(Html.EJ().Grid<object>("FlatGrid")
        .Datasource((IEnumerable<object>)ViewBag.dataSource) 
        .AllowPaging()
        .ToolbarSettings(toolbar =>
        {
            toolbar.ShowToolbar(true)
            .ToolbarItems(
                items =>
                {                    
                    items.AddTool(ToolBarItems.ExcelExport);
                    items.AddTool(ToolBarItems.WordExport);
                    items.AddTool(ToolBarItems.PdfExport);
                });
        }) 
        .Mappers(map => map.ExportToExcelAction("/Home/ExportToExcel").ExportToPdfAction("/Home/ExportToPdf").ExportToWordAction("/Home/ExportToWord"))
        .Columns(col =>
        {
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(90).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(90).Add();
            col.Field("EmployeeID").HeaderText("Employee Name").ForeignKeyField("EmployeeID").ForeignKeyValue("FirstName").DataSource((IEnumerable<object>)ViewBag.data).Width(75).Add();
            col.Field("Freight").HeaderText("Freight").Width(75).Format("{0:C}").Add();
            col.Field("ShipCity").HeaderText("Ship City").Width(80).Add();
        })
)

 

Code Behind

public class HomeController : Controller
    {
        
        public ActionResult Index()
        {
            ViewBag.dataSource = OrderRepository.GetAllRecords().ToList();  
            ViewBag.data = EmployeeRepository.GetAllRecords().ToList();
            return View();
        }        

        public void ExportToExcel(string GridModel)
        {
            ExcelExport exp = new ExcelExport();
            
            var dataSource = OrderRepository.GetAllRecords().ToList();
 
            GridProperties obj = ConvertGridObject(GridModel);
            obj.Columns[2].DataSource = EmployeeRepository.GetAllRecords().ToList();//set the dataSource for the foreign key column after deserializing the grid model properties.
            exp.Export(obj, dataSource, "Pedidos.xlsx", Syncfusion.XlsIO.ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
        
        public void ExportToWord(string GridModel)
        {
            WordExport exp = new WordExport();
            var dataSource = OrderRepository.GetAllRecords().ToList();
            GridProperties obj = ConvertGridObject(GridModel);
            obj.Columns[2].DataSource = EmployeeRepository.GetAllRecords().ToList();//set the dataSource for the foreign key column after deserializing the grid model properties.
            exp.Export(obj, dataSource, "Pedidos.docx", false, false, "flat-saffron");
        }
        
        public void ExportToPdf(string GridModel)
        {
            PdfExport exp = new PdfExport();
            var dataSource = OrderRepository.GetAllRecords().ToList();
            GridProperties obj = ConvertGridObject(GridModel);
            obj.Columns[2].DataSource = EmployeeRepository.GetAllRecords().ToList();//set the dataSource for the foreign key column after deserializing the grid model properties.
            exp.Export(obj, dataSource, "Pedidos.pdf", false, false, true, "flat-saffron");
        }
        
        private GridProperties ConvertGridObject(string gridProperty)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
            GridProperties gridProp = new GridProperties();
            foreach (KeyValuePair<string, object> ds in div)
            {
                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (property != null)
                {
                    Type type = property.PropertyType;
                    string serialize = serializer.Serialize(ds.Value);
                    object value = serializer.Deserialize(serialize, type);
                    property.SetValue(gridProp, value, null);
                }
            }
            return gridProp;
        }

 

Note:

A new version of Essential Studio for ASP.NET is available. Versions prior to the release of Essential Studio 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio for ASP.NET. Although Syncfusion will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below.

You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied