我有一个动态生成的DataTable
,其中包含许多不同的值:
Column1 | Column2 | Column3
----------------------------
230 | 265 | 272
270 | 235 | 235
250 | 235 | 254
250 | 225 | 259
我想以这种方式显示每个单元格的数据:
例如,在上表的Column1
的第一个单元格中,我想显示23.00%
,而不是230。它应该以这种方式计算:
First Cell of Column 1: 23.00% = (230 / (230 + 270 + 250 + 250)) * 100
例如,对于上表,结果应为:
Column1 | Column2 | Column3
-----------------------------
23.00% | 27.60% | 26.67%
27.00% | 24.48% | 23.04%
25.00% | 24.48% | 24.90%
25.00% | 23.44% | 25.39%
这是我使用的解决方案。 dtTab.Columns.Add(" TotalQty",GetType(Double))
Dim results As IEnumerable(Of Tuple(Of Object, Double)) = dtTab.Rows _
.Cast(Of DataRow) _
.GroupBy(Function(s As DataRow) s.Item("DateLabel")) _
.SelectMany(Function(rows) rows.Select(Function(row) Tuple.Create(row.Item("Date"), Convert.ToDouble(rows.Sum(Function(dataRow) Convert.ToDouble(dataRow.Item("QTY")))))))
For Each result As Tuple(Of Object, Double) In results
Dim dRow As DataRow() = dtTab.Select(String.Format("Date ='{0}' ", result.Item1.ToString()))
For Each row As DataRow In dRow
row.SetField(Of System.Nullable(Of Double))("TotalQty", result.Item2)
Next
Next
For Each row As DataRow In dtTab.Rows
Dim total As Double = row.Item("TotalQty")
total = Math.Round(total, 1)
row.SetField(Of System.Nullable(Of Double))("QTY", Convert.ToDouble(row.Item("QTY")) / total * 100)
Next
dtTab.Columns.Remove("TotalQty")
dtTab.AcceptChanges()
答案 0 :(得分:3)
您可以通过设置DataTable
的{{3}}属性,将计算列添加到DataColumn
。
然后,您可以使用列的Expression
属性格式化DataGridView
中的数据。
例如,假设您有Table1
包含Column1
,那么要添加计算列Column1Percent
,您可以执行此操作:
table1.Columns.Add("Column1Percent", double);
table1.Columns["Column1Percent"].Expression = "(Column1/SUM(Column1)) * 100";
this.DataGridView1.Columns["Column1Percent"].DefaultCellStyle.Format = "0.00'%'";
然后结果将是:
Column1 | Column1Percent
------------------------
1 | 20.00%
2 | 40.00%
2 | 40.00%