Search code examples
c#asp.net-mvcdatatable

Session datatable getting cleared based on another datatable


I am facing a weird issue in ASP.Net MVC. I am casting a DataTable session variable into another DataTable and when I clear items from second DataTable, they are also getting cleared from Session variable.

dataTable = (DataTable)Session["MyDataTable"];
dataTable.Rows.Clear(); //after this line Session["MyDataTable"] becomes empty

Session["MyDataTable"] contains DataTable and once I clear it from dataTable, that session datatable is also getting emptied. Any idea why?


Solution

  • Casting does not make a copy, so you are still dealing with a reference to the original DataTable. You would need to create a new DataTable and duplicate or clone the contents.