Casting data in a data table returns string rather than type inserted

Matthew Busselberg 21 Reputation points
2021-01-06T15:39:06.717+00:00

I have a custom class that holds the value of a cell which is put into a data table using the following command:

table.Rows.Add(error[i].GetValues());

GetValues() returns an array of a generic class: DataParcel<KeyType, DataType, ParentType>. In this particular case, the class instance is DataParcel<string, string, Record>. When I turn around and try to get the data of a particular cell using this command:

DataParcel<string, string, Record> parcel = (StudentDataParcel)table.Rows[e.RowIndex].ItemArray[0];     

This causes an invalid cast exception... what am I missing? It says that the data is of the string class instead of the class I tried to put in the table.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,457 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.7K Reputation points
    2021-01-06T16:06:26.377+00:00

    Probably you did not specify the type of columns. Try something like this:

    var table = new DataTable( );
    table.Columns.Add( "Col1", typeof( DataParcel<string, string, Record> ) );
    table.Columns.Add( "Col2", typeof( DataParcel<string, string, Record> ) );
    table.Columns.Add( "Col3", typeof( DataParcel<string, string, Record> ) );
    //...
    
    DataParcel<string, string, Record> parcel = (DataParcel<string, string, Record>)table.Rows[e.Rowndex].ItemArray[0];
    

    Specify enough number of columns. If you want to keep the array in a single, first column, then use table.Rows.Add((object)error[i].GetValues()) and make other obvious adjustments. (ItemArray[0] will represent an array).


0 additional answers

Sort by: Most helpful