簡體   English   中英

無法將對象從DBNull強制轉換為顯示的其他類型錯誤?

[英]Object cannot be cast from DBNull to other types error shown?

我的代碼是這樣

    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);
    }

在這里,我假設在Null的情況下將unitPrice設置為0。

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

如果可以有null值,請嘗試使用可為null的類型。

decimal? unitPrice = ...

可為空的類型是一種將null作為值的值類型。 然后可以檢查值

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

有關MSDN上的 nullables的更多信息。

但是我假設不應接收null,這將使計算變得不可能。 因此,我建議將獲取值封裝在try/catch塊中,如果某些調用引發異常,則從方法中返回。

您可以使用TryParse方法來確定是否可以從給定值轉換為十進制。如果不可能,則分配DBNull.Value

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

如果該值可以強制轉換為decimal則上述函數返回true
如果無法投放,則返回false

當需要在表列中插入Null ,應從代碼中插入DBNull.Value 因此您可以在無法進行強制轉換時發送DBNull.Value

注意:這里我使用三元?:運算符將整個事情寫在單行中
解:

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

問題是因為,從中獲取的數據值可能包含DBNull值,這意味着該值不存在。

因此,更改不存在的值的類型沒有意義。

允許null的解決方案是,將變量聲明為可為null的類型,這意味着它們能夠接受null值。

語法是:

datatype? variablename

霍普這有幫助。

我正在使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM