2013-11-22 56 views
1

我的代码是这样的对象不能从DBNull转换为显示的其他类型的错误?

private MyCatch _catch = new MyCatch("Description"); 

    decimal getTotalValue(GridView view, int listSourceRowIndex) 
    { 
     decimal unitPrice = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each")); //Object cannot be cast from DBNull to other types 
     decimal quantity = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Quantity")); 
     decimal discount = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "TaxPercentage")); 
     return unitPrice * quantity * (1 - discount); 
    } 

    private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e) 
    { 
     GridView view = sender as GridView; 
     if (e.Column.FieldName == "Totalototal" && e.IsGetData) e.Value = 
      getTotalValue(view, e.ListSourceRowIndex); 
    } 

回答

7

在这里,我认为,在空的情况下,它的单价设定为0

decimal unitPrice = view.GetListSourceRowCellValue(listSourceRowIndex, "Each") == DBNull.Value 
           ? 0 
           : Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each")); 
+0

嗨奈尔,Thankz很多 – Srihari

2

如果可以为空值,请尝试使用可空类型。

decimal? unitPrice = ... 

可为空的类型是接受null作为值的值类型。然后您可以检查价值

if (unitPrice.HasValue) // is there a value or null? 
    unitPrice.Value // do something with the value 

更多关于MSDN的空值。

但我认为不应该收到null,这将使计算不可能。因此,我建议将取回值封装在try/catch块中,并在某些调用引发异常时从方法返回。

+0

嗨Ondrej,可空的手段如何?我刚接触c#帮助我。 – Srihari

+0

@SriHari我会解释一下。 –

+0

@SriHari ..请看我的回答下面 –

1

可以使用TryParse方法来确定从给定的值强制类型转换是否可能十进制或not.if不可能分配DBNull.Value

语法:decimal.TryParse(value,out parameter)

上述函数返回true如果该值可被强制转换为decimal
回报铸造时false是不可能

当你需要插入Null到表列,则应该从代码中插入DBNull.Value。 因此当铸件不可能时您可以发送DBNull.Value

注:这里我已经使用三元?:操作员写在整个事件中单线
解决方案:

decimal result; 
decimal unitPrice =(decimal.TryParse(view.GetListSourceRowCellValue(listSourceRowIndex, "Each"),out result))?result:DBNull.Value; 
+0

嗨Sudhakar,我试过但在上面的错误,作为“最佳重载方法”无效的参数 – Srihari

+1

@SriHari:你应该声明变量的结果,现在检查我编辑的答案 –

+0

你的代码导致错误。你的意思是有'?result:0;'而不是'?result:DBNull.Value;'? – Trisped

1

的问题是怎么一回事,因为,其正在从5取出的数据值包含DBNull值,这意味着该值不存在。

因此,改变不存在的值的类型是没有意义的。

允许null的解决方案是将变量声明为可为空的类型,这意味着它们能够接受空值。

的synatax是:

datatype? variablename 

Hopw这有助于..

0

我使用的GridView与RowDataBound事件编程ASP.net VB,在某些行我已经从空数据库:

If e.Row.RowType = DataControlRowType.DataRow Then 
    If (DataBinder.Eval(e.Row.DataItem, "MyField") IsNot DBNull.Value) Then      
     myTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "MyField")) 
    End If  
End If 
相关问题