Object cannot be cast from DBNull to other types....

c00012 746 Reputation points
2021-07-21T08:18:39.86+00:00

I have a csv file contains following data: ProdCode, Lender, LoanAmt, APR, Terms, Payment.

I want to store these data into datatable so I defined it like this;

  1. define column:
    DataTable dt = new();
    dt.Columns.Add("Term", typeof(int));
    dt.Columns.Add("Payment", typeof(double));
    dt.Columns.Add("Principal", typeof(double));
    dt.Columns.Add("Interest", typeof(double));
    dt.Columns.Add("Balance", typeof(double));
  2. add row:
    for (int i = 0; i < Convert.ToInt32(off.Terms) * 12; i++)
    {
    DataRow row = dt.NewRow();
    if (i==0)
    {
    row["Balance"] = Convert.ToDouble(off.LoanAmt);
    }
    row["Term"] = i + 1;
    row["Payment"] = Convert.ToDouble(off.Payment);
    row["Interest"] = Convert.ToDouble(off.APR) / 12 * Convert.ToDouble(row["Balance"]);
    row["Principal"] = Convert.ToDouble(row["Payment"]) - Convert.ToDouble(row["Interest"]);
    row["Balance"] = Convert.ToDouble(row["Balance"]) - Convert.ToDouble(row["Principal"]);
    if(Convert.ToDouble(row["Balance"])<0.0)
    {
    row["Balance"] = 0.0;
    }
    dt.Rows.Add(row);
    }

after running above code, I got an error message:
116628-ice-screenshot-20210721-171213.png

If somebody pick my fault, I would be very appreciated.

thanks,
c0012

Developer technologies Windows Presentation Foundation
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 47,436 Reputation points
    2021-07-21T09:08:27.443+00:00

    If somebody pick my fault, I would be very appreciated.

    That's easy, you assign at the beginning ot the loop row["Balance"] only if i = 0. If i > 0 then row["Balance"] is later DBNull and as the error message already says, you can not convert DBNull to anything.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.