views:

54

answers:

1

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

+1  A: 

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.

jball
@jball: I tried to cast it into same type but when it didn't worked then i typecasted it to bigger type.
Shantanu Gupta
The `ItemAmount` column in the row has a type, and we don't know what it is, but you do; if you provide that type, it will work, I promise. That's how you're supposed to use `Field<T>`.
mquander
@Shantanu, I've added an explanation of the two options that you have, which, as mquander pointed out, depend on what type the column is, and is something that you'll need to know to solve this.
jball