简体   繁体   English

将DataRow值转换为float

[英]Casting DataRow value into float

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). 我正在使用DataRow ,我想用数字(从同一行的单元格中获取)将行中的每个值DataRow 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. 我一直在寻找将值转换为float的方法,例如从线程进行转换,但是强制转换给了我“指定强制转换无效”错误。

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. 我使用了两种方法将值转换为浮点数(使用Convert.toSingle和强制转换),但是两种方法都给了我错误。 Is there anything else I can do? 我还能做些什么吗? Or maybe is there something wrong in my code? 还是我的代码有问题?
ps tblSol is not empty and all variables are already declared. ps tblSol不为空,并且所有变量都已声明。

try float.Parse, but you need to convert the datarow to dynamic/string type for it to be compatible: 尝试float.Parse,但是您需要将数据行转换为动态/字符串类型才能兼容:

var test = (dynamic)fb[fb.Table.Columns.Count - 1];
float boat = float.Parse(test);

Or something similar using float.Parse 或者使用float.Parse类似的东西

You can try after converting it to String like this, 您可以像这样将其转换为String之后尝试,

float akun = float.Parse(fb[fb.Table.Columns.Count - 1].ToString()) /
        float.Parse(fb[u].ToString());

As noted in my comment, try casting the relevant columns to Decimal first. 如我的评论所述,请尝试首先将相关列转换为Decimal It is one of the explicitly supported DataTypes when accessing data from columns of DataRow instances; 从DataRow实例的列访问数据时,它是显式支持的DataType之一。 the valid types are listed in the MSDN DataColumn Reference page MSDN DataColumn参考页中列出了有效的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM