Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
A DataTable has an output as an Object.
I want to convert it to a Double.

These gave a Cast error:
C#
Convert.ToDouble(dt.Rows[i][dc]);

C#
(double)dt.Rows[i][dc];


Is there any way of changing an Object to a Double?

C#
double[,] f = new double[10000,10000];
foreach (DataColumn dc in dt.Columns)
{
    h = h + 1;
        for (int i = 0; i<=1500; i++)
        {
            f[h, i] = Convert.ToDouble(dt.Rows[i][dc]);                    }
    }
}


What I have tried:

C#
Convert.ToDouble(dt.Rows[i][dc]);

C#
(double)dt.Rows[i][dc];
Posted
Updated 1-May-16 19:12pm
v3
Comments
Karthik_Mahalingam 2-May-16 0:57am    
what is the exact error message?

The below code will take care of casting exception, but you will have to make sure that the table has valid numbers

C#
double[,] f = new double[10000, 10000];
           foreach (DataColumn dc in dt.Columns)
           {
               h = h + 1;
               for (int i = 0; i <= 1500; i++)
               {
                   string value = dt.Rows[i][dc] + "";
                   double d = 0;
                   double.TryParse(value, out d);
                   f[h, i] = d;
               }
           }
 
Share this answer
 
dc is a DataColumn type, not a string or numeric value. So you can't do this:
C#
dt.Rows[i][dc]
because dc is not a valid index expression.
Probably you want this:
C#
(double) dt.Rows[i][dc.Ordinal]
 
Share this answer
 
Comments
teledexterus 1-May-16 8:43am    
Even with Ordinal you still get a Cast error. Is there any other way to covert a datatable object to an array double? Or something like decimal that will convert from object? I have numbers like 123.4567 in my datatable.
OriginalGriff 1-May-16 8:46am    
Probably, you need to look at all your columns: does every cell in your datatable contain numeric values? Because you are running the same code - and so the same conversion - on every cell. If one column contains names, or dates, or ... it will fail.
Karthik_Mahalingam 2-May-16 0:56am    
Hi OriginalGriff
DataRow class has 6 overloading to get the object of current row

public object this[DataColumn column] { get; set; }
public object this[int columnIndex] { get; set; }
public object this[string columnName] { get; set; }
public object this[DataColumn column, DataRowVersion version] { get; }
public object this[int columnIndex, DataRowVersion version] { get; }
public object this[string columnName, DataRowVersion version] { get; }

so dt.Rows[i][dc] should work and it works, i have tested it.

JFI :)


Thanks
karthik
Convert.ToDouble(dt.Rows[i][dc].Tostring());

this will solve your problem+
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900