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

Excel export broken

2 Answers 102 Views
Grid
This is a migrated thread and some comments may be shown as answers.
David
Top achievements
Rank 1
David asked on 09 Oct 2012, 06:07 PM
Hi,

My grid was exporting okay before I added a footer. Kostadin helped me get the dynamic footer working, but after clicking the export button, I get a null reference exception during PreRender where the data items are accessed in order to populate the footer.

I have set EnableViewState to false, set export settings in the button control, and added an update panel with a post back trigger on the button to no avail.

protected void Button1_Click(object sender, EventArgs e)
{
    RadGrid grid = (RadGrid)PlaceHolder1.FindControl("RadGrid1");
 
    grid.AllowSorting = false;
    grid.Columns.FindByUniqueName("EditCommandColumn").Visible = false;
    grid.ExportSettings.ExportOnlyData = true;
    grid.ExportSettings.IgnorePaging = true;
    grid.ExportSettings.OpenInNewWindow = true;
    grid.ExportSettings.FileName = "WastewaterExport";
 
    grid.MasterTableView.ExportToExcel();
}

Any ideas?

Thanks,
David

2 Answers, 1 is accepted

Sort by
0
David
Top achievements
Rank 1
answered on 10 Oct 2012, 04:58 AM
Here is the code for your reference...

The null reference occurs on this line: "label1 = item.FindControl(columnName) as Label;"
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Text.RegularExpressions;
 
namespace WasteWater
{
 
    public partial class Spreadsheet : System.Web.UI.Page
    {
        protected global::System.Web.UI.WebControls.Literal dataRow;
 
        protected void Page_Init(object sender, System.EventArgs e)
        {
            DefineGridStructure();
        }
 
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
            RadGrid grid = (RadGrid)PlaceHolder1.FindControl("RadGrid1");
            RadAjaxManager1.AjaxSettings.AddAjaxSetting(grid, grid);
 
 
            if (!RadDatePickerStartingDate.SelectedDate.HasValue)
            {
                //RadDatePickerStartingDate.SelectedDate = DateTime.Today.AddMonths(-1);
                RadDatePickerStartingDate.SelectedDate = DateTime.Parse("2011-07-01");
            }
 
            if (!RadDatePickerEndingDate.SelectedDate.HasValue)
            {
                //RadDatePickerEndingDate.SelectedDate = DateTime.Today.AddMonths(-11);
                RadDatePickerEndingDate.SelectedDate = DateTime.Parse("2011-09-07");
            }
 
 
            if (Page.IsPostBack)
            {
                Label1.Text += "Post back!! <br>";
            }
            if (!Page.IsPostBack)
            {
                Label1.Text += "Page_Load; " + DateTime.Now.ToString() + "<br>";
            }
        }
 
        //void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        //{
        //    RadGrid grid = (RadGrid)PlaceHolder1.FindControl("RadGrid1");
        //    RadDatePicker startDate = (RadDatePicker)PlaceHolder1.FindControl("RadDatePickerStartingDate");
        //    DateTime StartingDate = (DateTime)startDate.SelectedDate;
        //    RadDatePicker endDate = (RadDatePicker)PlaceHolder1.FindControl("RadDatePickerEndingDate");
        //    DateTime EndingDate = (DateTime)startDate.SelectedDate;
        //    DataTable wastewaterGrid = WastewaterGrid.GetGrid(StartingDate, EndingDate);
        //    grid.DataSource = wastewaterGrid;
        //    grid.MasterTableView.DataSource = wastewaterGrid;
        //}
 
        /// <summary>
        /// DefineGridStructure
        /// </summary>
        /// <remarks>
        /// builds a dynamic grid
        /// </remarks>
        private void DefineGridStructure()
        {
            RadGrid RadGrid1 = new RadGrid();
            RadGrid1.ID = "RadGrid1";
 
            System.Drawing.Color disabledBackColor = System.Drawing.Color.AliceBlue;
            System.Drawing.Color defaultBorderColor = System.Drawing.Color.Black;
 
            RadGrid1.Width = Unit.Percentage(100);
            RadGrid1.Height = Unit.Pixel(850);
            RadGrid1.Style.Add("padding-right", "25px");
            RadGrid1.Style.Add("padding-left", "25px");
            RadGrid1.PageSize = 30;
            RadGrid1.GridLines = GridLines.Both;
            RadGrid1.AllowPaging = true;
 
            RadGrid1.AllowSorting = true;
            RadGrid1.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
            RadGrid1.ShowFooter = true;
            RadGrid1.AutoGenerateColumns = false;
            RadGrid1.ShowStatusBar = true;
 
//RadGrid1.NeedDataSource += RadGrid1_NeedDataSource;
RadGrid1.DataSourceID = "ObjectDataSource1";
            RadGrid1.ItemCreated += RadGrid1_ItemCreated;
            RadGrid1.ItemDataBound += RadGrid1_ItemDataBound;
            RadGrid1.UpdateCommand += RadGrid1_UpdateCommand;
            RadGrid1.PreRender += RadGrid1_PreRender;
 
            //RadGrid1.MasterTableView.GridLines = GridLines.Both;
            //RadGrid1.MasterTableView.BorderColor = System.Drawing.Color.Black;
            //RadGrid1.MasterTableView.BorderWidth = Unit.Pixel(1);
RadGrid1.EnableViewState = false;
RadGrid1.MasterTableView.EnableViewState = false;
//RadGrid1.MasterTableView.DataSourceID = "ObjectDataSource1";
 
            RadGrid1.MasterTableView.PageSize = 30;
            RadGrid1.MasterTableView.Height = Unit.Percentage(100);
            RadGrid1.MasterTableView.DataKeyNames = new string[] { "report_id" };
            RadGrid1.MasterTableView.EditMode = GridEditMode.InPlace;
 
            GridEditCommandColumn editColumn;
            editColumn = new GridEditCommandColumn();
            //editColumn.
            editColumn.UniqueName = "EditCommandColumn";
            editColumn.ItemStyle.BackColor = disabledBackColor;
            editColumn.ItemStyle.BorderColor = defaultBorderColor;
            editColumn.ItemStyle.BorderWidth = Unit.Pixel(1);
            //editColumn.ItemStyle.AddAttributesToRender
            RadGrid1.MasterTableView.Columns.Add(editColumn);
 
            GridColumnGroup headerGroupColumn;
            GridBoundColumn boundColumn = new GridBoundColumn();
            GridTemplateColumn templateColumn;
 
            boundColumn.DataField = "report_id";
            boundColumn.HeaderText = "ReportID";
            boundColumn.ItemStyle.BackColor = disabledBackColor;
            boundColumn.ItemStyle.BorderColor = defaultBorderColor;
            boundColumn.ItemStyle.BorderWidth = Unit.Pixel(1);
            boundColumn.ReadOnly = true;
            RadGrid1.MasterTableView.Columns.Add(boundColumn);
 
 
            RadGrid1.MasterTableView.AllowMultiColumnSorting = true;
            RadGrid1.MasterTableView.SortExpressions.Clear();
            GridSortExpression expression = new GridSortExpression();
            expression.FieldName = "report_id";
            expression.SortOrder = GridSortOrder.Ascending;
            RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);
 
 
 
            DataTable GroupHeaders = WastewaterGrid.GetGroupHeaders();
            DataTable Headers;
 
            foreach (DataRow groupRow in GroupHeaders.Rows)
            {
                String masterGroupName = groupRow["group_name"].ToString();
                String groupColumnHeader = groupRow["group_column_header"].ToString();
 
                Headers = WastewaterGrid.GetHeaders(masterGroupName);
 
                headerGroupColumn = new GridColumnGroup();
                headerGroupColumn.Name = masterGroupName;
                headerGroupColumn.HeaderText = groupColumnHeader;
                RadGrid1.MasterTableView.ColumnGroups.Add(headerGroupColumn);
 
                foreach (DataRow headerRow in Headers.Rows)
                {
                    String groupName = headerRow["group_name"].ToString();
                    String columnName = headerRow["column_name"].ToString();
                    String columnHeader = headerRow["column_header"].ToString();
                    String attributeType = headerRow["attribute_type"].ToString();
                    String dataType = headerRow["data_type"].ToString();
 
 
                     
                    if (!groupName.Equals(masterGroupName))
                    {
                        continue;
                    }
 
                    // Create numeric columns using templates
                    if (!dataType.Contains("varchar"))
                    {
                        templateColumn = new GridTemplateColumn();
                        templateColumn.ItemTemplate = new MyTemplate(columnName);
                        templateColumn.FooterTemplate = new MyFooterTemplate(columnName);
                        templateColumn.UniqueName = columnName;
                        templateColumn.HeaderText = columnHeader;
                        templateColumn.ColumnGroupName = masterGroupName;
 
                        if (!attributeType.Equals("ManualEntry"))
                        {
                            templateColumn.ItemStyle.BackColor = disabledBackColor;
                            templateColumn.ReadOnly = true;
                        }
 
                        RadGrid1.MasterTableView.Columns.Add(templateColumn);
                    }
                    else // Create bound text columns
                    {
                        boundColumn = new GridBoundColumn();
                        boundColumn.DataField = columnName;
                        boundColumn.UniqueName = columnName;
                        boundColumn.HeaderText = columnHeader;
                        boundColumn.ColumnGroupName = masterGroupName;
 
                        if (!attributeType.Equals("ManualEntry"))
                        {
                            boundColumn.ItemStyle.BackColor = disabledBackColor;
                            boundColumn.ReadOnly = true;
                        }
 
                        RadGrid1.MasterTableView.Columns.Add(boundColumn);
                    }
                }
            }
 
            this.PlaceHolder1.Controls.Add(RadGrid1);
        }
 
 
 
 
 
 
 
 
        /// <summary>
        /// RadGrid1_ItemCreated adds validation controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                GridEditableItem editItem = e.Item as GridEditableItem;
 
                DataTable Headers = WastewaterGrid.GetHeaders();
                foreach (DataRow row in Headers.Rows)
                {
                    String columnName = row["column_name"].ToString();
                    String dataType = row["data_type"].ToString();
 
                    GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)editItem.EditManager.GetColumnEditor(columnName);
                    TableCell cell = (TableCell)editor.TextBoxControl.Parent;
 
                    CustomValidator reqValidator = new CustomValidator();
                    editor.TextBoxControl.ID = columnName;  // +"CCID";
                    reqValidator.ControlToValidate = editor.TextBoxControl.ID;
                    reqValidator.ErrorMessage = "<font color=\"red\">Input is out of range for data type: \"" + dataType + "\".</font>";
 
                    switch (dataType)
                    {
                        case "bigint":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateInt64Input);
                            break;
                        case "decimal(10,2)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateDec102Input);
                            break;
                        case "decimal(10,3)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateDec103Input);
                            break;
                        case "decimal(4,1)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateDec41Input);
                            break;
                        case "decimal(5,1)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateDec51Input);
                            break;
                        case "decimal(6,1)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateDec61Input);
                            break;
                        case "int":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateInt32Input);
                            break;
                        case "varchar(25)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateVarchar25Input);
                            break;
                        case "varchar(255)":
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateVarchar255Input);
                            break;
                        default:
                            reqValidator.ServerValidate += new ServerValidateEventHandler(ValidateUnknownInput);
                            reqValidator.ErrorMessage = "<font color=\"red\">Unhandled data type: \"" + dataType + "\"; please contact technical support.</font>";
                            break;
                    }
                    reqValidator.SetFocusOnError = true;
                    cell.Controls.Add(reqValidator);
                }
            }
        }
 
 
 
 
        /// <summary>
        /// RadGrid1_ItemDataBound event manages business logic based on user roles and aggregates content for footers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            int? userRole = UserInfo.roleID;
            //Int32 userRole = 2;
            Label1.Text += "UserInfo.roleID=" + userRole + "\" <br>";
            Int32 today = int.Parse(DateTime.Today.AddMonths(-13).ToString("yyyyMMdd"));
            //Int32 today = int.Parse("20110907");
            String columnName;
            String attributeType;
            String dataType;
 
            GridTableCell gridCell;
            //dynamic cellText;
            String cellTestString;
            Boolean cellPopped = false;
            //dynamic cellValue;
            TextBox cellTextBox;
            //Boolean boolTest;
            //FooterItem footerItem;
 
            DataTable Headers = WastewaterGrid.GetHeaders();
 
            //if (e.Item is GridEditCommandColumn)
            //{
            //    GridEditCommandColumn editCommand = (GridEditCommandColumn)e.Item;
            //}
 
 
            if (e.Item is GridDataItem)
            {
                GridDataItem gridRow = (GridDataItem)e.Item;
                Int32 ReportID = int.Parse(gridRow.GetDataKeyValue("report_id").ToString());
                System.Drawing.Color defaultBorderColor = System.Drawing.Color.Black;
                System.Drawing.Color ableBackColor = System.Drawing.Color.White;
                System.Drawing.Color disabledBackColor = System.Drawing.Color.AliceBlue;
                System.Drawing.Color ableBorderColor = System.Drawing.Color.Lime;
 
                foreach (DataRow row in Headers.Rows)
                {
                    columnName = row["column_name"].ToString();
                    attributeType = row["attribute_type"].ToString();
                    dataType = row["data_type"].ToString();
 
                    gridCell = (GridTableCell)gridRow[columnName];
                    cellTestString = ((DataRowView)gridRow.DataItem)[columnName].ToString();
                    cellPopped = !String.IsNullOrEmpty(cellTestString);
 
                    //if (!dataType.Contains("varchar"))
                    //{
                    //    Label label1 = (Label)gridRow.FindControl("Label1");
 
 
                    //    //cellTestString = ((DataRowView)gridRow.DataItem)[columnName].ToString();
                    //    //cellText = (dynamic)((DataRowView)gridRow.DataItem)[columnName];
                    //}
                    //else
                    //{
                    //    gridCell = (GridTableCell)gridRow[columnName];
                    //}
 
 
 
                    gridCell.BorderColor = defaultBorderColor;
                    gridCell.BorderWidth = Unit.Pixel(1);
 
                    if (userRole == 1)
                    {
 
                        if (attributeType.Equals("ManualEntry"))
                        {
                            gridCell.BackColor = ableBackColor;
                            gridCell.BorderColor = ableBorderColor;
                            //Label1.Text += "today::columnName=" + columnName + "::cellText=\"" + cellText + "\" <br>";
 
                        }
                    }
                    else
                    {
                        if (attributeType.Equals("ManualEntry"))
                        {
                            if (!ReportID.Equals(today))
                            {
                                if (!cellPopped)
                                {
                                    gridCell.BackColor = ableBackColor;
                                    gridCell.BorderColor = ableBorderColor;
                                    //Label1.Text += "OLD EMPTY::ReportID=" + ReportID + "columnName=" + columnName + "::cellText=" + cellText + " <br>";
                                }
                                else
                                {
                                    gridCell.BackColor = disabledBackColor;
                                }
                            }
                            else
                            {
                                gridCell.BackColor = ableBackColor;
                                gridCell.BorderColor = ableBorderColor;
                                //Label1.Text += "NEW::ReportID=" + ReportID + "columnName=" + columnName + "::cellText=" + cellText + " <br>";
                            }
                        }
 
                        if (e.Item.IsInEditMode && !ReportID.Equals(today) && cellPopped)
                        {
                            cellTextBox = (TextBox)gridCell.Controls[0];
                            cellTextBox.BorderStyle = BorderStyle.None;
                            cellTextBox.BackColor = disabledBackColor;
                            cellTextBox.ReadOnly = true;
                            //Label1.Text += "EditMode::ReportID=" + ReportID + "columnName=" + columnName + "::cellText=" + cellText + " <br>";
                        }
                    }
                }
            }
            //www.telerik.com/help/search.aspx?pId=561&ppId=561&start=0&q=GridFooterItem
            //www.telerik.com/help/aspnet-ajax/m_telerik_web_ui_gridfooteritem__ctor.html
            //www.telerik.com/help/aspnet-ajax/allmembers_t_telerik_web_ui_gridfooteritem.html
            //else if (e.Item is GridFooterItem)
            //{
            //    GridFooterItem gridRow = (GridFooterItem)e.Item;
            //    int count = 0;
            //    dynamic min;
            //    dynamic max;
            //    dynamic sum;
 
            //    foreach (DataRow row in Headers.Rows)
            //    {
            //        columnName = row["column_name"].ToString();
            //        attributeType = row["attribute_type"].ToString();
 
            //        gridCell = (GridTableCell)gridRow[columnName];
            //        cellText = gridCell.Text;
            //        cellText = ((DataRowView)gridRow.DataItem)[columnName];
 
            //        footerItem = FooterAggregates[columnName];
 
            //        count += footerItem.count;
            //    }
            //}
 
 
            if ((e.Item is GridDataInsertItem) && e.Item.IsInEditMode)
            {
                Label1.Text += "insert operation triggered<br>";
            }
            else if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                Label1.Text += "Edit operation triggered<br>";
            }
        }
 
 
 
 
 
 
 
 
 
        void RadGrid1_PreRender(object sender, EventArgs e)
        {
            RadGrid radGrid1 = sender as RadGrid;
            Label label1;
            Boolean cellPopped;
            dynamic cellValue;
 
 
            DataTable Headers = WastewaterGrid.GetHeaders();
            Dictionary<String, FooterItem> FooterAggregates = new Dictionary<String, FooterItem>();
            FooterItem footerItem;
 
            String columnName;
            String attributeType;
            String dataType;
 
            foreach (DataRow row in Headers.Rows)
            {
                columnName = row["column_name"].ToString();
                dataType = row["data_type"].ToString();
 
                if (!dataType.Contains("varchar"))
                {
                    FooterAggregates.Add(columnName, new FooterItem(columnName));
                }
                else
                {
                    continue;
                }
            }
 
 
            foreach (GridDataItem item in radGrid1.MasterTableView.Items)
            {
                foreach (DataRow row in Headers.Rows)
                {
                    columnName = row["column_name"].ToString();
                    attributeType = row["attribute_type"].ToString();
                    dataType = row["data_type"].ToString();
 
                    if (!dataType.Contains("varchar"))
                    {
                        label1 = item.FindControl(columnName) as Label;
 
                        cellPopped = !String.IsNullOrEmpty(label1.Text);
 
                        if (cellPopped)
                        {
                            switch (dataType)
                            {
                                case "int":
                                    cellValue = Convert.ToInt32(label1.Text);
                                    break;
                                case "bigint":
                                    cellValue = Convert.ToInt64(label1.Text);
                                    break;
                                default:
                                    cellValue = Convert.ToDecimal(label1.Text);
                                    break;
                            }
 
                            footerItem = FooterAggregates[columnName];
                            footerItem.count += 1;
 
                            if (footerItem.min == null)
                            {
                                footerItem.min = cellValue;
                            }
                            else
                            {
                                if (footerItem.min > cellValue)
                                {
                                    footerItem.min = cellValue;
                                }
                            }
 
                            if (footerItem.max == null)
                            {
                                footerItem.max = cellValue;
                            }
                            else
                            {
                                if (footerItem.max < cellValue)
                                {
                                    footerItem.max = cellValue;
                                }
                            }
 
                            if (footerItem.sum == null)
                            {
                                footerItem.sum = cellValue;
                            }
                            else
                            {
                                footerItem.sum += cellValue;
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }
 
 
 
 
 
 
            foreach (DataRow row in Headers.Rows)
            {
                int? count = 0;
                decimal? sum = 0;
                decimal? min = decimal.MaxValue;
                decimal? max = decimal.MinValue;
                decimal avr = 0;
 
                columnName = row["column_name"].ToString();
                dataType = row["data_type"].ToString();
 
                if (!dataType.Contains("varchar"))
                {
                    footerItem = FooterAggregates[columnName];
 
                    sum = footerItem.sum;
                    count = footerItem.count;
                    min = footerItem.min;
                    max = footerItem.max;
 
                    if (count > 0)
                    {
                        avr = (decimal)(sum / count);
                        avr = Decimal.Round(avr, 2);
                    }
                    else
                    {
                        avr = 0;
                    }
 
                    GridFooterItem footer = radGrid1.MasterTableView.GetItems(GridItemType.Footer)[0] as GridFooterItem;
                    (footer.FindControl("templateFooter" + columnName + "Count") as TextBox).Text = count.ToString();
                    (footer.FindControl("templateFooter" + columnName + "Min") as TextBox).Text = min.ToString();
                    (footer.FindControl("templateFooter" + columnName + "Max") as TextBox).Text = max.ToString();
                    (footer.FindControl("templateFooter" + columnName + "Avg") as TextBox).Text = avr.ToString();
                }
                else
                {
                    continue;
                }
            }
        }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
        /// <summary>
        /// RadGrid1_UpdateCommand fires upsert and recalculate procedures on update.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            Label1.Text += " Table to be updated: " + e.Item.OwnerTableView.DataMember + "<br>";
 
            GridEditableItem editedItem = e.Item as GridEditableItem;
            GridEditManager editMan = editedItem.EditManager;
 
            Int32 ReportID = int.Parse(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["report_id"].ToString());
            String Login = "David-T420s\\davidk";
 
            foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
            {
                if (column.UniqueName.Equals("report_id"))
                {
                    continue;
                }
 
                if (column is IGridEditableColumn)
                {
                    Boolean isEditable = column.IsEditable;
                    String editColumnName = column.UniqueName.ToString();
 
                    IGridEditableColumn editableCol = (column as IGridEditableColumn);
                    if (editableCol.IsEditable)
                    {
                        IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
 
                        if (editor is GridTextColumnEditor)
                        {
                            String Datum = (editor as GridTextColumnEditor).Text.Trim();
 
                            DataTable Headers = WastewaterGrid.GetHeaders();
                            foreach (DataRow row in Headers.Rows)
                            {
                                String columnName = row["column_name"].ToString();
                                String dataType = row["data_type"].ToString();
 
                                if (columnName.Equals(editColumnName))
                                {
 
                                    try
                                    {
                                        WastewaterGrid.UpsertDatum(ReportID, editColumnName, Datum, Login);
                                    }
                                    catch (Exception ex)
                                    {
                                        Label1.Text += "<strong>Unable to set value of column '" + column.UniqueName + "'</strong>  <br>" + ex.Message;
                                        RadAjaxManager1.Alert("Unable to set value of column: " + column.UniqueName + "; " + ex.Message);
                                        e.Canceled = true;
                                        break;
                                    }
 
                                }
                            }
                        }
                    }
                }
            }
 
            try
            {
                WastewaterGrid.ReCalculate(ReportID);
            }
            catch (Exception ex)
            {
                RadAjaxManager1.Alert("Unable to run ReCalculate: " + ex.Message);
                e.Canceled = true;
            }
        }
 
        private class MyFooterTemplate : ITemplate
        {
            private string _columnName;
            protected TextBox textBox1;
            protected TextBox textBox2;
            protected TextBox textBox3;
            protected TextBox textBox4;
 
            public MyFooterTemplate(string columnName)
            {
                _columnName = columnName;
            }
 
            public void InstantiateIn(System.Web.UI.Control container)
            {
                textBox1 = new TextBox();
                textBox2 = new TextBox();
                textBox3 = new TextBox();
                textBox4 = new TextBox();
                textBox1.ID = "templateFooter" + _columnName + "Count";
                textBox2.ID = "templateFooter" + _columnName + "Min";
                textBox3.ID = "templateFooter" + _columnName + "Max";
                textBox4.ID = "templateFooter" + _columnName + "Avg";
                Table table = new Table();
                TableRow row1 = new TableRow();
                TableRow row2 = new TableRow();
                TableRow row3 = new TableRow();
                TableRow row4 = new TableRow();
                TableCell cell11 = new TableCell();
                TableCell cell12 = new TableCell();
                TableCell cell21 = new TableCell();
                TableCell cell22 = new TableCell();
                TableCell cell31 = new TableCell();
                TableCell cell32 = new TableCell();
                TableCell cell41 = new TableCell();
                TableCell cell42 = new TableCell();
                row1.Cells.Add(cell11);
                row1.Cells.Add(cell12);
                row2.Cells.Add(cell21);
                row2.Cells.Add(cell22);
                row3.Cells.Add(cell31);
                row3.Cells.Add(cell32);
                row4.Cells.Add(cell41);
                row4.Cells.Add(cell42);
                cell11.BorderStyle = BorderStyle.None;
                cell12.BorderStyle = BorderStyle.None;
                cell21.BorderStyle = BorderStyle.None;
                cell22.BorderStyle = BorderStyle.None;
                cell31.BorderStyle = BorderStyle.None;
                cell32.BorderStyle = BorderStyle.None;
                cell41.BorderStyle = BorderStyle.None;
                cell42.BorderStyle = BorderStyle.None;
                table.Rows.Add(row1);
                table.Rows.Add(row2);
                table.Rows.Add(row3);
                table.Rows.Add(row4);
                //cell11.Text = "Count:";
                cell12.Controls.Add(textBox1);
                //cell21.Text = "Min:";
                cell22.Controls.Add(textBox2);
                //cell31.Text = "Max:";
                cell32.Controls.Add(textBox3);
                //cell41.Text = "Avg:";
                cell42.Controls.Add(textBox4);
                container.Controls.Add(table);
 
 
            }
        }
 
        private class MyTemplate : ITemplate
        {
            private string _columnName;
            protected Label label1;
 
            public MyTemplate(string columnName)
            {
                _columnName = columnName;
            }
 
            public void InstantiateIn(Control container)
            {
                label1 = new Label();
                label1.ID = _columnName;
                label1.DataBinding += new EventHandler(label1_DataBinding);
                container.Controls.Add(label1);
            }
 
            void label1_DataBinding(object sender, EventArgs e)
            {
                Label label = (Label)sender;
                GridDataItem container = (GridDataItem)label.NamingContainer;
                label.Text = (((DataRowView)container.DataItem)[_columnName]).ToString();
            }
        }
 
 
        /// <summary>
        /// FooterItem provides storage for accumulating footer aggregate information
        /// </summary>
        public class FooterItem
        {
            private String _columnName;
            private int _count;
            private dynamic _min;
            private dynamic _max;
            private dynamic _sum;
 
            public FooterItem(String str)
            {
                _columnName = str;
                _count = 0;
            }
 
            public String columnName
            {
                get
                {
                    return _columnName;
                }
                set
                {
                    _columnName = value;
                }
            }
 
            public int count
            {
                get
                {
                    return _count;
                }
                set
                {
                    _count = value;
                }
            }
 
            public dynamic min
            {
                get
                {
                    return _min;
                }
                set
                {
                    _min = value;
                }
            }
 
            public dynamic max
            {
                get
                {
                    return _max;
                }
                set
                {
                    _max = value;
                }
            }
 
            public dynamic sum
            {
                get
                {
                    return _sum;
                }
                set
                {
                    _sum = value;
                }
            }
        }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
        private void ValidateInt32Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                Match match;
                String TestString;
                String IntPattern = @"^\d+$";
 
                match = Regex.Match(Datum, IntPattern);
                if (match.Success)
                {
                    try
                    {
                        TestString = Int32.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
                else
                {
                    e.IsValid = false;
                }
            }
        }
 
        private void ValidateInt64Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                Match match;
                String TestString;
                String IntPattern = @"^\d+$";
 
                match = Regex.Match(Datum, IntPattern);
                if (match.Success)
                {
                    try
                    {
                        TestString = Int64.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
                else
                {
                    e.IsValid = false;
                }
            }
        }
 
        private void ValidateDec102Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                String TestString;
                Int32 stringLength = Datum.Length;
 
                if (!ValidateDecimalFormat(Datum, stringLength, 10, 2))
                {
                    e.IsValid = false;
                }
                else
                {
                    try
                    {
                        TestString = Decimal.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
 
        private void ValidateDec103Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                String TestString;
                Int32 stringLength = Datum.Length;
 
                if (!ValidateDecimalFormat(Datum, stringLength, 10, 3))
                {
                    e.IsValid = false;
                }
                else
                {
                    try
                    {
                        TestString = Decimal.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
 
        private void ValidateDec41Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                String TestString;
                Int32 stringLength = Datum.Length;
 
                if (!ValidateDecimalFormat(Datum, stringLength, 4, 1))
                {
                    e.IsValid = false;
                }
                else
                {
                    try
                    {
                        TestString = Decimal.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
 
        private void ValidateDec51Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                String TestString;
                Int32 stringLength = Datum.Length;
 
                if (!ValidateDecimalFormat(Datum, stringLength, 5, 1))
                {
                    e.IsValid = false;
                }
                else
                {
                    try
                    {
                        TestString = Decimal.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
 
        private void ValidateDec61Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                String TestString;
                Int32 stringLength = Datum.Length;
 
                if (!ValidateDecimalFormat(Datum, stringLength, 6, 1))
                {
                    e.IsValid = false;
                }
                else
                {
                    try
                    {
                        TestString = Decimal.Parse(Datum).ToString();
                        e.IsValid = true;
                    }
                    catch (OverflowException)
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
 
        private void ValidateVarchar25Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                if (Datum.Length > 25)
                {
                    e.IsValid = false;
                }
                else
                {
                    e.IsValid = true;
                }
            }
        }
 
        private void ValidateVarchar255Input(object sender, ServerValidateEventArgs e)
        {
            String Datum = e.Value;
            if (String.IsNullOrEmpty(Datum))
            {
                e.IsValid = true;
            }
            else
            {
                if (Datum.Length > 255)
                {
                    e.IsValid = false;
                }
                else
                {
                    e.IsValid = true;
                }
            }
        }
 
 
        private void ValidateUnknownInput(object sender, ServerValidateEventArgs e)
        {
            e.IsValid = false;
        }
 
 
        private Boolean ValidateDecimalFormat(String Datum, int stringLength, int precision, int scale)
        {
            Match match;
            String IntPattern = @"^\d+$";
            Int32 decimalIndex = Datum.IndexOf(".");
 
            if (decimalIndex > 0)
            {
                Int32 fractionalLength = stringLength - decimalIndex - 1;
 
                if (fractionalLength > scale)
                {
                    return false;
                }
 
                Int32 integralLength = stringLength - fractionalLength - 1;
 
                if (integralLength > (precision - scale))
                {
                    return false;
                }
 
                String integralString = Datum.Substring(0, decimalIndex);
                String fractionalString = Datum.Substring(decimalIndex + 1, fractionalLength);
                match = Regex.Match(integralString, IntPattern);
                if (match.Success)
                {
                    match = Regex.Match(fractionalString, IntPattern);
                    if (match.Success)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
 
            }
            else if (stringLength > (precision - scale))
            {
                return false;
            }
            else
            {
                match = Regex.Match(Datum, IntPattern);
                if (match.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
 
 
        /// <summary>
        /// Button1_Click is the export button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            RadGrid grid = (RadGrid)PlaceHolder1.FindControl("RadGrid1");
 
            grid.AllowSorting = false;
            grid.Columns.FindByUniqueName("EditCommandColumn").Visible = false;
            grid.ExportSettings.ExportOnlyData = true;
            grid.ExportSettings.IgnorePaging = true;
            grid.ExportSettings.OpenInNewWindow = true;
            grid.ExportSettings.FileName = "WastewaterExport";
 
            grid.MasterTableView.ExportToExcel();
        }
        /// <summary>
        /// Button2_Click is the footer toggle
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            RadGrid grid = (RadGrid)PlaceHolder1.FindControl("RadGrid1");
 
            Boolean footerShowing = grid.ShowFooter;
 
            if (footerShowing)
            {
                grid.ShowFooter = false;
            }
            else
            {
                grid.ShowFooter = true;
            }
        }
         
    }
}
0
Kostadin
Telerik team
answered on 12 Oct 2012, 12:16 PM
Hi David,

I guess it is not working because you set the ExportOnlyData property to true. In this case the export removes the controls which are in the footers and that is why you recieve null reference exception. Try setting the property to false in order to fix it.

Regards,
Kostadin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
David
Top achievements
Rank 1
Answers by
David
Top achievements
Rank 1
Kostadin
Telerik team
Share this question
or