locked
problem with c# converting null to integer RRS feed

  • Question

  • User1868852945 posted

    For my MVC web application my model has...

    public Int32 table_start { get; set; }

    my repository provides to the Controller...

    table_start = Convert.ToInt32(dr["table_start"]),

    and the razor code does math on the field...

    int table_start_total = 0;

    table_start_total += Convert.ToInt32(item.table_start);

    I cannot trust that the database query will never return null, so I used the Toint32 which is supposed to convert null to zero, but I get error...

    Object cannot be cast from DBNull to other types.

    In debug the item.table_start shows "" coming into the razor math which causes the error.  The query will only return null, zero or an int.  Why is the razor math getting a string and is this simple attempt the wrong way to do it?  What is the right way to pass integers from DB to view page?  Thanks.

    Monday, July 9, 2018 2:39 PM

Answers

  • User-1171043462 posted

    int table_start_total = 0;

    table_start_total += Convert.ToInt32(item.table_start);

    Try this way

    if(item.table_start != null && item.table_start != DBNull.Value)
    {
       table_start_total += Convert.ToInt32(item.table_start);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 9, 2018 5:21 PM

All replies

  • User-492460945 posted

    Hi gundrej,

    Are you using stored procedure with an output parameter? if so, it must be returning null value from procedure. Please check once.

    Thanks,

    RajeshV.

    Monday, July 9, 2018 2:48 PM
  • User1868852945 posted

    Yes, null can on occasion be returned from the stored procedure and I cannot change the stored procedure to replace null with zero.

    Monday, July 9, 2018 3:01 PM
  • User-492460945 posted

    Hi gundrej,

    You can skip null using simple if condition checking whether outparameter is null or not. check this link below,.

    https://stackoverflow.com/questions/18810375/stored-procedure-returns-null-as-output-parameter

    Thanks,

    RajeshV.

    Monday, July 9, 2018 3:10 PM
  • User-1171043462 posted

    int table_start_total = 0;

    table_start_total += Convert.ToInt32(item.table_start);

    Try this way

    if(item.table_start != null && item.table_start != DBNull.Value)
    {
       table_start_total += Convert.ToInt32(item.table_start);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 9, 2018 5:21 PM