question

seihyungoh avatar image
0 Votes"
seihyungoh asked seihyungoh edited

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

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

windows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

OlafHelper-2800 avatar image
0 Votes"
OlafHelper-2800 answered seihyungoh edited

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.