-1

i am filling datatable from db.below code

SUM(CONVERT(float, REPLACE(Quantity, CHAR(0), ''))) as Quantity,

from datatable now i need to convert into float so i tried below code

float s1 = 0;
foreach (DataRow _dr in obj_dt.Rows)
{
   s1 = _dr.Field<float>("Quantity");
}

but its showing error

Specified cast is not valid.

where i made error.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Happy
  • 1,105
  • 5
  • 17
  • 25

3 Answers3

0

do this:

s1 = Convert.ToDouble( _dr["Quantity"]);

or

s1 = (float) _dr["Quantity"];
T McKeown
  • 12,971
  • 1
  • 25
  • 32
0

Below code worked for me : float.Parse(_dr["Quantity"].ToString());

Vihana Kewalramani
  • 915
  • 11
  • 14
-3

you are doing down casting in wrong manner, you have need to correct you statement as

float s1 = 0;
foreach (DataRow _dr in obj_dt.Rows)
{
 s1 = Convert.ToSingle(_dr["Quantity"]);
}

done

SiwachGaurav
  • 1,918
  • 2
  • 17
  • 16
  • You shouldn't convert a numeric value to a string, just to parse it again as a numeric value, just to unbox it. – Servy Jan 15 '14 at 18:55