Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception occuring while using T Field<T> in my code

I am getting InvalidCastException when i am trying to use this code. I am not been able to resolve how to use Field. Plz help me out

DataTable _Transaction= new DataTable();
float NetAmount=0;
//Records inserted into Table 

  for (int i = 0; i < _Transaction.Rows.Count; i++)
            {
                NetAmount += _Transaction.Rows[i].Field<object>("ItemAmount");
            }

EDIT I actually want to retrieve value at specified columnName and Row no from a dataTable. _Transaction is a name of table here

like image 609
Shantanu Gupta Avatar asked Mar 20 '26 17:03

Shantanu Gupta


1 Answers

You'll need to cast or convert _Transaction.Rows[i].Field<object>("ItemAmount") to the same type as NetAmount so that the += operater will be operating on a single type.

For example, if NetAmount is a decimal and the field is also a decimal use Field<decimal> instead of Field<object>. If the field is not a decimal, use Convert.ToDecimal on it.

like image 53
jball Avatar answered Mar 22 '26 05:03

jball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!