Home > Mobile >  How do I do a sum of gridview cells from selected rows in WPF using c#?
How do I do a sum of gridview cells from selected rows in WPF using c#?

Time:01-31

If I had to do a sum of a specific columns of selected rows in a DataGridView, I would usually do something like

decimal total = myDGV.SelectedRows.OfType<DataGridViewRow>()
    .Sum(t => Convert.ToDecimal(t.Cells[2].Value));

How do I do that in WPF?

If I did:

decimal total = myGrid.SelectedItems.OfType<DataGridRow>()
    .Sum(t => Convert.ToDecimal(t.Cells[2].Value));

I get an error 'System.Windows.Controls.DataGridRow' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'System.Windows.Controls.DataGridRow' could be found (are you missing a using directive or an assembly reference?) (CS1061)

Help please.

CodePudding user response:

I'm not that knowledgeable in LINQ, but this should do the job:

List<decimal> targetCells = new List<decimal>();

for (int i = 0; i < myGrid.SelectedItems.Count; i  )
{
    DataRowView row = (DataRowView)myGrid.SelectedItems[i];
    targetCells.Add(Convert.ToDecimal(row[2].ToString()));
}

decimal total = targetCells.Sum();

Maybe someone else will show you how to do this in a single LINQ query (if it can be done) :).

  •  Tags:  
  • Related