Reputation: 1145
I need to remove few columns from datatable and bind to grid view. So I tried below code:
obj_dt = obj_backup.sale_where_date();
grd_excel.DataSource = obj_dt;
obj_dt_pdf = obj_dt;
// to remove few columns in data table
obj_dt_pdf.Columns.Remove("Location");
obj_dt_pdf.Columns.Remove("No Opn Stack");
obj_dt_pdf.Columns.Remove("Expiry Date");
obj_dt_pdf.Columns.Remove("Discount %");
obj_dt_pdf.Columns.Remove("Discount Amt");
obj_dt_pdf.Columns.Remove("TAX");
obj_dt_pdf.Columns.Remove("VAT");
obj_dt_pdf.Columns.Remove("Entry Date");
dataGridView_wd_pdf.DataSource = obj_dt_pdf;
Problem is after removing columns in obj_dt_pdf its also removing from obj_dt. I need to remove in obj_dt_pdf alone.
where I made error?
Upvotes: 4
Views: 846
Reputation: 48465
DataTable
is a class, and classes are "reference types", this means that when you assign it to another variable you just have two variables pointing to the same instance.
You would need to create a "copy" of the object, and lucky for you it just so happens that DataTable
has a Copy()
method, so you can do this:
obj_dt_pdf = obj_dt.Copy();
Do not get this confused with the Clone()
method, which will only include the structure, and not the data
Upvotes: 0
Reputation: 236328
When you are assigning obj_dt
to obj_dt_pdf
you are not copying DataTable
- you just make copy of reference to DataTable
instance. So, that makes both variables point to same DataTable
instance:
obj_dt_pdf = obj_dt;
Create copy of DataTable instead (use DataTable.Copy() method to copy both table structure and data):
obj_dt_pdf = obj_dt.Copy();
Now obj_dt_pdf
points to copy of original DataTable
, and changes of copy will not affect original DataTable
instance.
Upvotes: 0
Reputation: 67948
You need to use Copy
, so something like this:
obj_dt_pdf = obj_dt.Copy();
instead of this:
obj_dt_pdf = obj_dt;
The Copy
method will copy both the structure and the data.
Upvotes: 0
Reputation: 460380
Then don't use the same reference. You can use Clone
to get a DataTable
with the same schema of a table (without data) or Copy
to create a clone with all data:
obj_dt = obj_backup.sale_where_date();
var copy = obj_dt.Copy();
copy.Columns.Remove("Location");
copy.Columns.Remove("No Opn Stack");
// ...
dataGridView_wd_pdf.DataSource = copy;
Upvotes: 1