铸造/不铸造时C#无限值错误

时间:2012-01-26 16:10:36

标签: c# winforms casting

我认为这将是一个简单的问题,我想我错过了一些东西。

if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))

这段代码给了我一个错误,当施放不能是一个无限的数字时。

我也尝试过:

if (((int)row.Cells["Pareto"].Value <= 50) && ((string)row.Cells["Pareto"].Value != null))
if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != ""))

任何帮助都会很棒!

我使用C#在visual studio 10中使用winforms。

错误:“从数字转换时,值必须小于无限”

如果您感兴趣,请参阅更多代码:

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            //countpg
            //countPg++;
            pgtothold = Convert.ToSingle(row.Cells["Qty"].Value);
            countPg += pgtothold;

            //if (((int)row.Cells["Pareto"].Value <= 50) && (row.Cells["Pareto"].Value != null))
            if ((Convert.ToDouble(row.Cells["Pareto"].Value)) && ((int)row.Cells["Pareto"].Value <= 50)
            {
                //top 50
                //top++;
                tempTop = Convert.ToSingle(row.Cells["Qty"].Value);
                top += tempTop;
            }
            else
                if (((int)row.Cells["Pareto"].Value > 50) && ((int)row.Cells["Pareto"].Value <= 100) && (row.Cells["Pareto"].Value != ""))
                {
                    //50-100
                    tempMidt = Convert.ToSingle(row.Cells["Qty"].Value);
                    tmid += tempMidt;
                }
                else

3 个答案:

答案 0 :(得分:3)

if ((row.Cells["Pareto"].Value != null) && ((int)row.Cells["Pareto"].Value <= 50))

我想你想要这个。如果该事物为空,则不会评估AND的其余部分。

答案 1 :(得分:1)

我建议您使用:

var data =  System.Convert.ToInt32(row.Cells["Pareto"].Value);
   if( data <=50 )
   {
    ----
   }
如果内容是DBNull(如果这是可接受的),则

将失败为0,因此您的代码将变得更清晰,更安全。

答案 2 :(得分:0)

数据表的结果很可能是十进制类型。所以试试这个:

if (((decimal)row.Cells["Pareto"].Value <= 50.0m) && (row.Cells["Pareto"].Value != null))