C# .NET - Getting values from each row for one column

Asked By Saurabh Tiwari on 29-Dec-10 01:21 PM

Hi,

My problem is I m not getting values from each row for one column I m using the following code nd getting one exception at the underlined code

for (int i = 0; i < (dt.Rows.Count); i++)
{

double ext = Convert.ToDouble(dt.Rows[i]);
double bill = (ext * 1024);
bill = (bill / 100);
The exception is
"Unable to cast object of type 'System.Data.DataRow' to type 'System.IConvertible'."
Plz help me
Thank you!
anil soni replied to Saurabh Tiwari on 29-Dec-10 01:33 PM
THe ths is you are trying to convert a DataRow to Double which is not possible
dt.Rows[i] will retur you the i th row of the DataTable and now you have to use indexer of DataRow to get the particular value of a cell e.g.

dt.Rows[i][0]

or if you want to fetch the cell value by column of row i then you can use

dr.Rows[i]["columnName"]

so your code should be something like
double ext = Convert.ToDouble(dt.Rows[i][0]);
Mohan Raj Aryal replied to Saurabh Tiwari on 29-Dec-10 02:38 PM
You can also use following statement to make sure the value is double: 

//assume that dt is a DataTable
 
for each(DataRow dr in dt.Rows)
{
  if( Double.TryParse(dr.dr.ItemArray[0].ToString())==true)
  {
    double ext=Double.Parse(dr.ItemArray[0].ToString();
  }
}