Reputation: 25
I'm working with DataRow
and I want to divide every value in the row with a number(taken from a cell from the same row). I've been searching ways to convert the values into float, like from this thread, but casting gives me "Specified cast is not valid" error.
List<DataTable> tblsol = new List<DataTable>();
DataTable now = tblsol.Last();
while (true)
{
DataRow fb = now.Rows[v];
DataRow fb2 = now.Rows[w];
float akun = (float)fb[fb.Table.Columns.Count - 1] /
(float)fb[u];
if (akun > (float)fb2[fb2.Table.Columns.Count - 1] /
(float)fb2[u])
{
if (w == now.Rows.Count - 1) { v = w; break; }
else { v++; w++; }
}
else
{
if (w == now.Rows.Count - 1) { break; }
else { w++; }
}
}
DataRow bk = now.Rows[v];
float angkun = Convert.ToSingle(bk[u]);
for (int dc = 1; dc < now.Columns.Count;dc++)
{
bk[dc] = Convert.ToSingle(bk[dc]) / angkun;
}
I used 2 methods to convert the value into float (using Convert.toSingle
and casting), but both ways gave me error. Is there anything else I can do? Or maybe is there something wrong in my code?
p.s. tblSol
is not empty and all variables are already declared.
Upvotes: 2
Views: 7637
Reputation: 10184
As noted in my comment, try casting the relevant columns to Decimal
first. It is one of the explicitly supported DataTypes when accessing data from columns of DataRow instances; the valid types are listed in the MSDN DataColumn Reference page
Upvotes: 1
Reputation: 1984
You can try after converting it to String
like this,
float akun = float.Parse(fb[fb.Table.Columns.Count - 1].ToString()) /
float.Parse(fb[u].ToString());
Upvotes: 1
Reputation: 703
try float.Parse, but you need to convert the datarow to dynamic/string type for it to be compatible:
var test = (dynamic)fb[fb.Table.Columns.Count - 1];
float boat = float.Parse(test);
Or something similar using float.Parse
Upvotes: 1