简体   繁体   中英

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

My code is this

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

Here I assume, in case of Null it set the unitPrice to 0.

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

If there can be null value try using nullable types.

decimal? unitPrice = ...

A nullable type is a value type that accepts null as a value. You can then check value

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

More about nullables on MSDN .

But I assume that null should not be received, it would make the calculation impossible. Therefore I would advise to encapsulate fetching values in a try/catch block instead and return from method if some of the calls throws an exception.

you can use TryParse method to identify whether cast is possible from given value to decimal or not.if not possible assign the DBNull.Value

Syntax: decimal.TryParse(value,out parameter)

the above function return true if the value can be castable to decimal
return false when casting is not possible

when you need to insert Null into table column you should insert DBNull.Value from the code. so you can send DBNull.Value when the casting is not possible.

Note: here i have used ternary ?: operator to write the whole thing in single line
Solution:

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

The Problem is beacuse , the data values that are being fetched from may contain DBNull values which means that value does not exists.

So, it makes not sense in changing the type of the value that has not existed.

The solution to allow null is , declare the variable as nullable types that means they are capable of accepting null values.

The synatax is:

datatype? variablename

Hopw this helps..

I am programming ASP.net VB using GridView with RowDataBound event, in some rows I have nulls from database:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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