Copying a DataTable without using the .Copy method
I have a DataTable that's had people wire into it's different column changed events, ect...
I need to clear the table out occasionally and fill it with new data, from a different datatable.
I was just using targetTable = sourceTable.Copy(), but then the people above me loose the events they've wired into.
I was thinking that I could write an extension method for DataTables to do this, so I could reuse it if the situation ever arose again.
The part where I get hung up is that if I'm doing it in a generic way, then I want to completely transfer the schema from the source table to the target table.
Is there any easy way of doing this? I was looking at just comparing the columns to make s开发者_如何学JAVAure the names/types matched, but then I thought I could make it more robust if I could also transfer the schema.
It looks like there is a way to transfer the schema by using the ReadXMLSchema and WriteXMLSchema, but I'm wondering if their isn't an eaiser way.
http://msdn.microsoft.com/en-us/library/system.data.datatable.merge.aspx transfers the schema and all data, preserving changes or row states if you need.
DataTable.Merge(dt2, true, MissingSchemaAction.Add);
Have you tried
YourTable.Clear() -- just to remove records, but no any other definitions YourTable.Merge( TheOtherTable) -- to merge records from one into the other.
精彩评论