This is a migrated thread and some comments may be shown as answers.

RadGrid Exporting with Item Template Programmatically

1 Answer 39 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Kris
Top achievements
Rank 1
Kris asked on 12 Aug 2014, 09:58 PM
I've come across an issue with exporting the radgrid to csv and excel files when using the item template. I've poked around a bit on the forums to see what solutions are already present and from what I've gathered I should set the text field of my item template columns before exporting. The problem I am running into is when I try to find the control it keeps returning null (or in this case Object reference not set to an instance of an object).

My Grid Exporting Event:
protected void RadGridInventory_GridExporting(object source, GridExportingArgs e)
        {
            foreach (GridDataItem item in RadGridInventory.MasterTableView.Items)
            {
                item["AccountId"].Text = (item.FindControl("lControl") as HyperLink).Text; //returns null
                item["Status"].Text = (item.FindControl("statusCode") as LiteralControl).Text; //returns null
            }
 
            if (e.ExportType == ExportType.Excel)
            {
                string customText = "<h1 style='text-align:center;'>Inventory Report for " + _applicationUser.Customer.Name + "</h1>";
                customText += "<p style='text-align:center;'><b>Current Date:</b> " + DateTime.Now + "<br />";
 
                if(RadDatePickerStarting.SelectedDate != null && RadDatePickerEnding.SelectedDate != null){
                    customText += "<b>Date Range Covered:</b> " + RadDatePickerStarting.SelectedDate + " - " + RadDatePickerEnding.SelectedDate + "<br />";
                } else {
                    customText += "<b>Date Range Covered:</b> " + RadComboBoxChoices.SelectedItem.Text + "<br />";
                }
 
                customText += "<b>Clients:</b>";
                foreach (var client in ClientSelector1.SelectedClients)
                {
                    customText += " " + client.Name + ",";
                }
 
                customText = customText.TrimEnd(',');
                customText += "</p>";
                e.ExportOutput = e.ExportOutput.Replace("<body>", "<body>" + customText);
            }
        }

The RadGrid:
public void BuildGrid(IList<UserReportColumn> userReportColumns)
        {
            RadGridInventory.FilterMenu.EnableEmbeddedSkins = false;
            RadGridInventory.PreRender += RadGridInventory_PreRender;
            RadGridInventory.EnableLinqExpressions = false;
 
            RadGridInventory.AllowFilteringByColumn = true;
            RadGridInventory.AllowPaging = true;
            RadGridInventory.AllowSorting = true;
            RadGridInventory.GridLines = GridLines.None;
            RadGridInventory.ShowGroupPanel = true;
            RadGridInventory.AutoGenerateColumns = false;
            RadGridInventory.CssClass = "RadGridAccounts";
            RadGridInventory.EnableViewState = false;
            RadGridInventory.Width = Unit.Pixel(1090);
            RadGridInventory.EnableEmbeddedSkins = false;
 
            RadGridInventory.ClientSettings.AllowDragToGroup = true;
            RadGridInventory.ClientSettings.Resizing.AllowColumnResize = true;
            RadGridInventory.ClientSettings.Resizing.AllowRowResize = true;
            RadGridInventory.ClientSettings.Resizing.ResizeGridOnColumnResize = true;
            RadGridInventory.ClientSettings.Resizing.ClipCellContentOnResize = true;
            RadGridInventory.ClientSettings.Resizing.EnableRealTimeResize = false;
            RadGridInventory.ClientSettings.Resizing.ShowRowIndicatorColumn = false;
 
            RadGridInventory.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
            RadGridInventory.ExportSettings.HideStructureColumns = true;
            RadGridInventory.ExportSettings.ExportOnlyData = true;
            RadGridInventory.ExportSettings.IgnorePaging = true;
 
            RadGridInventory.MasterTableView.DataKeyNames = new string[] { "AccountId" };
            RadGridInventory.MasterTableView.ClientDataKeyNames = new string[] { "AccountId" };
            RadGridInventory.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;
            RadGridInventory.MasterTableView.CommandItemSettings.ShowExportToExcelButton = true;
            RadGridInventory.MasterTableView.CommandItemSettings.ShowExportToCsvButton = true;
            RadGridInventory.MasterTableView.CommandItemSettings.ShowAddNewRecordButton = false;
            RadGridInventory.GridExporting += new OnGridExportingEventHandler(RadGridInventory_GridExporting);
 
            RadGridInventory.MasterTableView.Width = Unit.Percentage(100);
 
            var accountColumn = userReportColumns.FirstOrDefault(x => x.ReportColumn.ColumnName == "AccountId");
            if (accountColumn != null)
            {
                var templateColumn = new GridTemplateColumn();
                RadGridInventory.MasterTableView.Columns.Add(templateColumn);
                templateColumn.ItemTemplate = new AccountColumnTemplate("AccountId");
                templateColumn.DataField = "AccountId";
                templateColumn.SortExpression = "AccountId";
                templateColumn.UniqueName = "AccountId";
                templateColumn.GroupByExpression = "Group By AccountId";
                templateColumn.HeaderText = accountColumn.ColumnHeaderEval;
            }     
             
            foreach (var column in userReportColumns)
            {
                if (column.ReportColumn.ColumnName == "AccountId") continue;
 
                if (column.ReportColumn.ColumnName == "Status") continue;
 
                var boundColumn = new GridBoundColumn();
                RadGridInventory.MasterTableView.Columns.Add(boundColumn);
 
                AccountGridHelpers.SetupBoundColumn(boundColumn, column);
            }
 
            var statusColumn = userReportColumns.FirstOrDefault(x => x.ReportColumn.ColumnName == "Status");
            if (statusColumn != null)
            {
                var statusTemplateColumn = new GridTemplateColumn();
                RadGridInventory.MasterTableView.Columns.Add(statusTemplateColumn);
                statusTemplateColumn.ItemTemplate = new StatusColumnTemplate("Status");
                statusTemplateColumn.DataField = "Status";
                statusTemplateColumn.UniqueName = "Status";
                statusTemplateColumn.AllowFiltering = true;
                statusTemplateColumn.SortExpression = "Status";
                statusTemplateColumn.HeaderText = statusColumn.ColumnHeaderEval;
            
        }


The Account Id Template:
public class AccountColumnTemplate : ITemplate
    {
        protected HyperLink lControl;
        private string _colname;
        public AccountColumnTemplate(string cName)
        {
            _colname = cName;
        }
 
        public void InstantiateIn(System.Web.UI.Control container)
        {
            lControl = new HyperLink {ID = "lControl"};
            lControl.DataBinding += lControl_DataBinding;
            container.Controls.Add(lControl);
        }
 
        public void lControl_DataBinding(object sender, EventArgs e)
        {
            var l = (HyperLink)sender;
            var container = (GridDataItem)l.NamingContainer;
 
            l.Attributes["href"] = "/Secure/AccountDetail.aspx?account=" + ((AccountDtoBase)container.DataItem).AccountId;
 
            l.Text = ((AccountDtoBase)container.DataItem).AccountId;
        }
    }

Any point in the right direction would be greatly appreciated. I'd really like to avoid having to set ExportOnlyData to false (another solution I've seen floating around) since it really ends up just not looking very nice.

1 Answer, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 1
answered on 13 Aug 2014, 07:06 AM
Hi Kris,

To access the rows of the grid you can use the ItemCreated event of the RadGrid. Please try the following code snippet.

C#:
RadGridInventory.ItemCreated += new GridItemEventHandler(RadGridInventory_ItemCreated);
RadGridInventory.ItemCommand += new GridCommandEventHandler(RadGridInventory_ItemCommand);
 
bool isExport = false;
void RadGridInventory_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.ExportToExcelCommandName)
    {
     isExport = true;
    }
}
 
void RadGridInventory_ItemCreated(object sender, GridItemEventArgs e)
{
  if (isExport)
   {
     foreach (GridDataItem item in RadGridInventory.MasterTableView.Items)
     {
      //Access controls
      HyperLink hlklControl = (HyperLink)item.FindControl("lControl");
      LiteralControl lcstatusCode = (LiteralControl)item.FindControl("statusCode");
     }
   }
}
void RadGridInventory_GridExporting(object sender, GridExportingArgs e)
{
    if (e.ExportType == ExportType.Excel)
    {
        //Code
    }
}

Thanks,
Princy
Tags
Grid
Asked by
Kris
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 1
Share this question
or