Summing DataGridView columns using Linq in C#.net
How to sum datagrid view using Linq in C#.net
Wanna find sum of particular column in DataGridView control ? We can loop through it., wait....
Sometimes Linq statement can do the same efficiently. See the example.
var gross = from DataGridViewRow row in dataGridView1.Rows where row.Cells[colAmount.Index].FormattedValue.ToString().Trim().Length != 0 && row.Cells[colAmount.Index].FormattedValue != null select row.Cells[colAmount.Index].FormattedValue;
var grossVal = gross.Sum(c => Convert.ToDouble(c));
In the above code, we check for null and empty row and then select all the rows which has the value.
The Linq statement return a list, from the List we can run aggregate functions such sum.
Our sum statement is a inline function which convert the string value into number.
In effect we cached all null, string errors.