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.
Step 1: Create a console application and add the Student class with the properties as below. Step 2: In Main method, create a list of students as below. Step 3: Now we are going to convert this list object to a DataTable. For that we need to create a new class and a conversion method as below.
There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.
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);
Use this handy function to convert a regular DataTable
to a typed DataTable
.
VB
Public Shared Function ConvertToTypedDataTable(Of T As {Data.DataTable, New})(dtBase As Data.DataTable) As T
Dim dtTyped As New T
dtTyped.Merge(dtBase)
Return dtTyped
End Function
Usage
Dim dtTyped = ConvertToTypedDataTable(Of dataset1.MyTypedDataTable)(MyUntypedDataTable)
C#
public static T ConvertToTypedDataTable<T>(System.Data.DataTable dtBase) where T : Data.DataTable, new()
{
T dtTyped = new T();
dtTyped.Merge(dtBase);
return dtTyped;
}
Usage
dataset1.MyTypedDataTable dtTyped = ConvertToTypedDataTable<dataset1.MyTypedDataTable>(MyUntypedDataTable);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With