2013-11-22 57 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 
相關問題