Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting generic datatable to typed datatable

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.

like image 713
callisto Avatar asked Sep 09 '09 09:09

callisto


People also ask

How copy data from list to DataTable in C#?

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.

Can we convert DataTable to list?

There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.


2 Answers

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);
like image 142
Thomas Levesque Avatar answered Sep 22 '22 15:09

Thomas Levesque


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);
like image 26
Carter Medlin Avatar answered Sep 24 '22 15:09

Carter Medlin