Why am I losing my session here?
I have a page with a button that, when clicked, fetches data from the database and stores it in a datatable and binds it to a GridView. This datatable is stored in the Session variable. I also have a button that exports the specified columns from the data file to an excel file, but when I click the export button a second time, I get the following error:
An object reference is not set on an object instance.
What seems to be happening on 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 column name to "Licensee"; however, when I call Export a second time, it looks for dtExport.Columns ["Business"] again, which it doesn't find, so it throws an error. I just need to check if the column has already been renamed to allow 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 the column name, does it persist even if you get a new DataTable from the session again?
source to share