Jump to content

Somar Coluna de Datagridview


Chamuanza
 Share

Recommended Posts

Um Bem Aja a todos de novo

Preciso de uma ajuda  😛

Pretendo somar as celulas de uma coluna de datagridview que tenham como BackColor Color.White.

Para isso estou a testar com o seguinte código:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

       
        'Coloca a linha com cor e somente de leitura
    
        Me.OutrasContasDataGridView.Rows(3).DefaultCellStyle.BackColor = Color.Silver
        Me.OutrasContasDataGridView.Rows(3).ReadOnly = True

      

    End Sub

Private Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click

        'Somar a coluna 9
        Dim SomaColuna As Decimal

        For Each coluna As DataGridViewRow In OutrasContasDataGridView.Rows
            If Me.OutrasContasDataGridView.RowsDefaultCellStyle.BackColor <> Color.Silver Then
                SomaColuna = SomaColuna + coluna.Cells(9).Value
            End If
        Next

        'Fotmata as cx. texto
        Label3.Text = Format(Convert.ToDecimal(SomaColuna), "##,##0.00 €")
    End Sub

No entanto obtenho o somatório de todas as celulas da coluna 9, incluindo o valor da celula que tem  BackColor = Color.Silver

O que é que me falta no código acima?

Obrigado desde já pela atenção

Link to comment
Share on other sites

Só mesmo assim por acaso, experimenta:

For Each coluna As DataGridViewRow In OutrasContasDataGridView.Rows
            If Me.OutrasContasDataGridView.RowsDefaultCellStyle.BackColor = Color.White Then
                SomaColuna = SomaColuna + coluna.Cells(9).Value
            End If
        Next
Link to comment
Share on other sites

Tinhas uma falha no ciclo, aqui vai o que pretendes:

 Try
            Dim SomaColuna As Decimal
            For Each coluna As DataGridViewRow In DataGridView1.Rows
                If Me.DataGridView1.Rows(coluna.Index).DefaultCellStyle.BackColor <> Color.Silver Then
                    SomaColuna = SomaColuna + coluna.Cells(0).Value
                End If
            Next
            Label1.Text = Format(Convert.ToDecimal(SomaColuna), "##,##0.00 €")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.