WPF C# Get the Total Sum of a DataGrid Column

一笑奈何 提交于 2020-01-03 01:40:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!