在没有附加查询的情况下对WPF datagrid列的值求和?

时间:2012-08-11 15:10:04

标签: c# .net wpf wpf-controls wpfdatagrid

我正在填充以下WPF数据网格:

enter image description here

使用以下方法:

private void ButtonFilterWorkflowWhenClick(object sender, RoutedEventArgs e)
{
    var db = new DatabaseHandle();



    dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);


    labelWorkflowLastLoaded.Content = "Last Loaded at " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " with " +
                              dataGridWorkflow.Items.Count.ToString(CultureInfo.InvariantCulture) + " total events.";


}

其中引用了以下类对象:

public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)
{
    string queryString = "[marlin].[support_retrieve_workflow_history]";

    using (SqlConnection connection = new SqlConnection(GetConnectionString()))
    {
        using (var cmd = new SqlCommand(queryString, connection))
        {
            connection.Open();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("date_from", startDate.Date);
            cmd.Parameters.AddWithValue("date_to", endDate.Date);

            var reader = cmd.ExecuteReader();

            var dt = new DataTable();
            dt.Load(reader);

            connection.Close();
            return dt.DefaultView;

        }
    }

}

我正试图找到一种方法,我可以找到总列的总和,这样我就可以将它添加到我的标签但没有成功。我可以通过第二个查询执行此操作,但我希望尽可能避免这种情况。我该如何处理这个问题?

1 个答案:

答案 0 :(得分:1)

您可能需要枚举DataView中的行,例如:

dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);
DataView dv = (DataView)dataGridWorkflow.ItemsSource;
DataRowCollection drc = dv.Table.Rows;
IEnumerator rowEnum = drc.GetEnumerator();
int sum = 0;
while (rowEnum.MoveNext())
{
    sum += (int)((DataRow)rowEnum.Current)[3];//assuming the 'Total' column has index 3.
}
labelWorkflowLastLoaded.Content = "Last Loaded at " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " with " + sum.ToString(CultureInfo.InvariantCulture) + " total events.";

修改:我对其进行了更改,以便您可以复制并粘贴到代码中。