Guangzhan
Guangzhan

Reputation: 49

DataRow.Field<T>(float Column) throws invalid cast exception

IDE Visual Studio 2015
**.NET"" 4.5
Platform WinForms

I have a database table with a column [UsedSize] FLOAT. When querying this table and storing the values in local variables I get an invalid cast exception; sample code:

SqlDataAdapter sda = new SqlDataAdapter(cmdText, conn);
DataTable dt = new DataTable();
sda.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    InfoLibrary ir = new InfoLibrary();
    ir.LibraryID = row.Field<int>("LibraryID");
    ir.Name = row.Field<string>("Name");
    ir.UsedSize = row.Field<float>("UsedSize");
    ir.TotalSize = row.Field<float>("TotalSize");
    ir.TotalFileCount = row.Field<int>("TotalFileCount");                   
    ilList.Add(ir);
}

When stepping the execution and performing a "Quick Watch" on the faulty line I discovered that, by changing the line to row.Field("TotalSize"), the cell value type is zero. Why would this happen when, in the table definition, this is clearly and float?

Upvotes: 0

Views: 1632

Answers (1)

HasaniH
HasaniH

Reputation: 8402

SQL Server float should map to a .Net Double see here

Upvotes: 3

Related Questions