问题
I need to sum all of the values in a DataGrid every time an event is fired (probably CelLEditEnding) and display it in a label. I have the following code:
private void tblData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
double sum = 0;
//System.Windows.MessageBox.Show(tblData.SelectedItems.Count.ToString());
for (int i = 0; i < tblData.SelectedItems.Count; i++)
{
TextBlock tb = tblData.Columns[3].GetCellContent(tblData.SelectedItems[i]) as TextBlock;
double test = Convert.ToDouble(tb.Text);
sum = sum + test;
lblTotal.Content = "$ " + sum.ToString();
//System.Windows.MessageBox.Show(sum.ToString());
The problem is that only one row is affected, the one row that actually gets summed up and displayed into the label is random. As you can see I added a mesage box to show me the total number of rows that are in the DataGrid, the result is 1 every time. I don't know how to get around this issue, I am very noob to programming and have issues with the technical jargon. Any help is greatly appreciated.
回答1:
for (int i = 0; i < tblData.Items.Count; ++i)
{
//(decimal.Parse((tblData.SelectedCells[3].Column.GetCellContent(item) as TextBlock).Text))
sum += (decimal.Parse((tblData.Columns[3].GetCellContent(tblData.Items[i])as TextBlock).Text));
}
回答2:
for (int i = 0; i < dataGrid.Items.Count; ++i)
sum += (decimal.Parse((dataGrid.Columns[4].GetCellContent(dataGrid.Items[i]) as TextBlock).Text));
来源:https://stackoverflow.com/questions/31128357/wpf-c-sharp-get-the-total-sum-of-a-datagrid-column