views:

868

answers:

3

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.

+1  A: 

You cannot cast the DataTable to a MarketValueDataTable, for the simple reason that it doesn't inherit from it.

What you need to do is instantiate a new MarketValueDataTable, then copy the data from the DataTable into it.

Try something like:

MarketValueDataTable myTable = new MarketValueDataTable();
StringWriter writer = new StringWriter();
theDataTable.WriteXml(writer);
myTable.ReadXml(new StringReader(writer.ToString()));

(I haven't tested this)

Tor Haugen
+3  A: 

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);
Thomas Levesque
I luv SO!Thanks.
callisto
A: 

If your datatable is a generic table then it can't be cast to a MarketValueDataTable.

One thing you can try is to create a new MarketValueDataTable object and manually add rows to it. By stepping through the rows of your generic datatable and then stepping through the columns of each row you could use reflection to set the property values of a new MarketValueDataTableRow.

Something like the following (warning - pseudocode):

MarketValueDataTable mv = new MarketValueDataTable();
foreach(DataRow row in table.Rows)
{

   MarketValueDataTableRow mvrow = mv.NewRow();
   foreach(DataColumn col in table.Columns)
   {
      PropertyInfo colProperty = mvrow.GetType().GetProperty(col.Name);
      colProperty.SetValue(mvRow, row[col]);
   }
   mv.Rows.Add(mvrow);

}

You get the general idea. Step through the rows of the generic table and use reflection to find the matching properties in the specific typed data row. This should work (I have used the same approach earlier), but the code must be modified to match your requirements.

Rune Grimstad