Getting DataTable Field Value Results in InvalidCastException

0

In my application I have a DataTable defined as such:

DataTable MyTable = new DataTable("myTableName");
MyTable.Columns.Add(new DataColumn("myUInt16Field", typeof(ushort)));
DataRow dr = MyTable.NewRow();
dr["myUInt16Field"] = default(ushort);
MyTable.Rows.Add(dr);

The table is not data-bound. Later, data is saved to the field:

byte[] byteData = new byte[] { 0x96, 0x01 };
ushort ushortData = BitConverter.ToUInt16(byteData, 0)
MyTable.Rows[0].SetField<ushort>("myUInt16Field", ushortData);

Later still, I have this line of code to fetch the data stored in the field:

ushort myUInt16Data = MyTable.Rows[0].Field<ushort>("myUInt16Field");

That line is where I get the error: "System.InvalidCastException: 'Specified cast is not valid.'"

When I inspect the data in the Watch window, I see it has a value of 0x00000196 (expected) with a type of object {int}, which I think explains the InvalidCastException. What I don't understand is, why/how is the field being assigned to type int when I declared it as ushort when the table column was created?

I'm using Visual Studio 2017 and .NET Framework 4.6.2. Is there possibly something that I've overlooked, or is this expected behavior?

c#
exception
datatable
type-conversion
asked on Stack Overflow Jan 17, 2019 by Jim Fell • edited Jan 17, 2019 by Jim Fell

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0