I have a page with a button that when I click, it retrieves data from a database and stores it into a datatable and binds it to a GridView. This datatable is stored in a Session variable. I also have a button that exports specified columns from the datatable to an excel file, but when I click the export button a second time, I get the following error:
Object reference not set to an instance of an object.
It seems to happen at this line:
dtExport.Columns["Business"].ColumnName = "Licensee";
I think I know why, the original column is called "Business", but when I export, I want to export the column header as Licensee, so I change the ColumnName to "Licensee"; however when I call Export a second time, it is looking for dtExport.Columns["Business"] again which it does not find, so it throws an error. Do I just need to check if the column as already been renamed to resolve this or is there another way?
Here is the code that does the Export:
private void ExportExcel()
{
DataTable dtExport = Session["dtSearchResults"] as DataTable;
dtExport.Columns["Business"].ColumnName = "Licensee";
List<int> columnSelect = new List<int>();
columnSelect.Add(dtExport.Columns["Licensee"].Ordinal);
columnSelect.Add(dtExport.Columns["Name"].Ordinal);
columnSelect.Add(dtExport.Columns["Address"].Ordinal);
columnSelect.Add(dtExport.Columns["City"].Ordinal);
columnSelect.Add(dtExport.Columns["State"].Ordinal);
columnSelect.Add(dtExport.Columns["Zip"].Ordinal);
int[] ColList = columnSelect.ToArray();
GridViewExportUtil.ExportDetails(dtExport,
ColList,
GridViewExportUtil.ExportFormat.Excel,
string.Format("{0}_{1}-{2}-{3}{4}",
"SearchResults",
DateTime.Now.Month,
DateTime.Now.Day,
DateTime.Now.Year,
".xls"));
}
When you change a ColumnName, does it persit, even if you get a new DataTable from Session again?