Casting generic datatable to typed datatable

callisto picture callisto · Sep 9, 2009 · Viewed 24.3k times · Source

I need to reuse a DataAccess method prescribed by client. This method returns a vanilla datatable. I want to cast this datatable to my Typed datatable. The amount of columns and their types will match. The exception message "Unable to cast object of type 'System.Data.DataTable' to type 'MarketValueDataTable'." is very clear, but how do I fix it?

Had a look at casting-a-base-type-to-a-derived-type, but could not see how to make that work.

I cannot populate the datatable with a datareader, can only use the client's DataAccess method.

Answer

Thomas Levesque picture Thomas Levesque · Sep 9, 2009

The cast could only work if the table returned by the method was actually an instance of MarketValueDataTable. If it's not, all you can do is copy the data to an instance of MarketValueDataTable. You could for instance use the Merge method :

DataTable data = GetData();
MarketValueDataTable myData = new MarketValueDataTable();
myData.Merge(data);