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?

0


source to share


3 answers


I am assuming the value is by reference, and when the Business column name changes, it also changes in the session. I would try this:



DataTable dtExport = (Session["dtSearchResults"] as DataTable).Copy();

      

+3


source


You don't get a new DataTable that you get the same one that you originally generated. Any changes you make to it will be visible on subsequent uses.



In this case, I will rename the column back to its original name after export.

+1


source


This is a terrible solution, but ... add

dtExport.Columns["Licensee"].ColumnName = "Business";

      

at the end of your method to restore the original situation. And add some error / existence checking.

+1


source







All Articles