如何动态计算vb.net的列和行

时间:2014-11-28 03:11:46

标签: vb.net

早上好,所有...... 我需要帮助,如何动态计算vb.net中datagrid的列和行?我已经制作但仍然是statis如果我添加新数据,计算结果不会移动到新列。我有编码,我已经做了..

    DGV2.Columns.Add("Total Km", "Total Km")
    'DGV2.Columns.Add("Percentage", "Percentage")
    Dim bykdata As Integer = DGV2.RowCount - 1
    Dim bykkolom As Integer = DGV2.ColumnCount + 1
    Dim a As Integer
    Dim b As Integer
    Dim c As Integer
    Dim d As Integer
    Dim g As Integer
    Dim f As Integer
    Dim h As Integer
    Dim i As Integer 'looping
    Dim j As Integer 'looping
    Dim k As Integer
    Dim m As Integer
    Dim n As Integer
    Dim o As Integer
    Dim v As Integer
    'Dim w As Integer
    'Dim x As Integer
    Dim tot As Integer

    'ambildata
    For i = 0 To bykdata
        v = DGV2.Item(2, i).Value
        a = DGV2.Item(3, i).Value
        b = DGV2.Item(4, i).Value
        c = DGV2.Item(5, i).Value
        d = DGV2.Item(6, i).Value
        g = DGV2.Item(7, i).Value
        f = DGV2.Item(8, i).Value
        h = DGV2.Item(9, i).Value
        k = DGV2.Item(10, i).Value
        m = DGV2.Item(11, i).Value
        n = DGV2.Item(12, i).Value
        o = DGV2.Item(13, i).Value
        c = v + a + b + c + d + g + f + h + k + m + n + o
        DGV2.Item(14, i).Value = c.ToString
    Next

    For j = 0 To bykdata
        a = DGV2.Item(3, j).Value
        tot = tot + a
        DGV2.Item(15, j).Value = tot.ToString
    Next

2 个答案:

答案 0 :(得分:0)

您的变量名称不是很具描述性,很难理解您在做什么。但这是我能做到的快捷方式。

Dim total As Integer = 0

For i = 0 To bykdata
    Dim rowSum As Integer = 0

    For columnIndex = 2 To 13
        rowSum += DGV2.Item(columnIndex, i).Value
    Next

    total += DGV2.Item(3, j).Value

    DGV2.Item(14, i).Value = rowSum.ToString
    DGV2.Item(15, j).Value = total.ToString
Next

答案 1 :(得分:0)

对于底部的列总和,您可以使用它。你必须添加一行

DGV2.Rows(DGV2.RowCount - 1).Cells("Total Km").Value = Convert.ToDouble(CType(DGV2.DataSource, DataTable).Compute("SUM(Total Km)", ""))

对于水平单元格求和,你必须像这样循环,你必须像你一样添加一列总数

        For Each row As DataGridViewRow In DGV2.Rows
            For Each cell As DataGridViewCell In row.Cells
                    If Not cell.Value Is DBNull.Value Then
                        sum1 += cell.Value
                    End If
            Next
            row.Cells("Total KM").Value = sum1
            sum1 = Nothing
        Next