在DataGridView中为分组值添加“计数”列

时间:2017-03-30 11:50:00

标签: c# winforms sharepoint datagridview

我正在从SharePoint列表填充DataGridView,它可以正常工作。

我需要DataGridView中的一个新列,它显示每个分组列表项的计数。

到目前为止,我有:

if (collListItem.Count != 0)
{
    var dtCoaching = new DataTable();

    dtCoaching.Columns.AddRange(new[]
    {
       new DataColumn("Call Type"),  new DataColumn("Count")
    });

    foreach (var oListItem in collListItem)
    {
        dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
    }

    dtCoaching = dtCoaching.AsEnumerable()
    .GroupBy(r => new { Col1 = r["Call Type"]})
    .Select(g => g.OrderBy(r => r["Call Type"]).First())
    .CopyToDataTable();

    if (dataGridViewCallType!= null)
    {
        dataGridViewCallType.DataSource = dtCoaching;
    }                   
}

我见过很多输出到Console的解决方案,这很棒,但我需要DataTable绑定到DataGridView,而不是输出到控制台。

这是迄今为止的输出:

Click for Screenshot

我只需要计数列就可以了!

由于

戴维

1 个答案:

答案 0 :(得分:0)

找到答案,需要克隆DataTable并使用Count列构建一个新的。

            if (collListItem.Count != 0)
            {
                var dtCoaching = new DataTable();

                dtCoaching.Columns.AddRange(new[]
                {
                    new DataColumn("Call Type"),  new DataColumn("Count")
                });

                foreach (var oListItem in collListItem)
                {
                    dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
                }

                var result = from row in dtCoaching.AsEnumerable()
                             group row by row.Field<string>("Call Type") into grp
                             select new
                             {
                                 CallType = grp.Key,
                                 CallCount = grp.Count()
                             };

                DataTable dtCoachingClone = new DataTable();
                dtCoachingClone = dtCoaching.Clone();

                foreach (var item in result)
                {
                    DataRow newRow = dtCoachingClone.NewRow();
                    newRow["Call Type"] = item.CallType;
                    newRow["Count"] = item.CallCount;
                    dtCoachingClone.Rows.Add(newRow);
                }

                if (dataGridViewCallType != null)
                {
                    dataGridViewCallType.DataSource = dtCoachingClone;
                }

                return;
            }