I have a datatable similar to
Rank Year Value
1 1990 1234556.5676
2 2000 12313.1212
3 2010 131242.1234
I have the following code which I wrote with the help of the following thread: How to select min and max values of a column in a datatable?
double dMaxValue = 0;
foreach (DataRow dr in dsView.Tables[0].Rows)
{
double dValue = dr.Field<double>("Value");
dMaxValue = Math.Max(dMaxValue, dValue);
}
This is throwing an error "Specified cast is not valid". What am I missing here and also how can I get the value of the year column once I find the MAX Value? The year needs to be returned to the calling program.
EDIT- (SOLUTION): With the help of SLacks I figured out how to accomplish the task. Firstly, I found that the data in my datatable was of type string so converted the value to double and determine the maximum value. Then used a variable to find the corresponding year.
string sYear = string.Empty;
double dMaxValue = double.MinValue;
foreach (DataRow dr in dsView.Tables[0].Rows)
{
double dValue = Convert.ToDouble(dr.Field<string>("Value"));
if (dValue > dMaxValue)
{
sYear = dr["Year"].ToString();
}
dMaxValue = Math.Max(dMaxValue, dValue);
}
return sYear;