Unable to Cast

  • Thread starter Thread starter Danny Ni
  • Start date Start date
D

Danny Ni

Hi,

I am having problem with the following code snippet:


DataTable dt = getDataFromXLS(@"c:\test\Customers.xls"); //getDataFromXLS
function reads an Excel file and return a sheet as a datatable

for (int i=0;i<dt.Rows.Count;i++)
{
DataRow dr=dt.Rows;
int intCustomerID = (int) dr[0]; //This line fails with error: An
unhandled exception of type 'System.InvalidCastException' occurred

//some other codes go here

}

I looked at the Excel file, the data on the first column are all integers.
But when I tried to debug my application, dr[0].GetType returns
System.Double.

How do I cast it to int?

TIA
 
Hi,

I looked at the Excel file, the data on the first column are all
integers. But when I tried to debug my application, dr[0].GetType returns
System.Double.

How do I cast it to int?

There is no way to cast it, as there is no implicit cast from double to int,
you have to use Convert.ToInt32
 
int.Parse(dr[0].ToString());

but you can also use UInt16, UInt32, etc to do it as well
 
int.Parse(dr[0].ToString());

but you can also use UInt16, UInt32, etc to do it as well

Going through a string value is a pretty inefficient way of working,
and it doesn't show what's going on.

I'd prefer (int)(double)dr[0] to show that it's actually returning a
double, but that we want it as an int.
 
Back
Top