locked
Agregar linea de totales al final de una lista de un datagridview RRS feed

  • Pregunta

  • Buenas tardes, tengo un datagridview el cual cargo con datos de una tabla de Sql server y necesito agregar al final de la lista cargada una linea de totales a como muestro en el siguiente ejemplo:

    si alguien me puede apoyar se lo agradecería mucho.

    jueves, 22 de julio de 2021 17:13

Respuestas

  • Hola Reynaldo,

    Me horroriza Visual Basic, pero ... retoqué tu código, fijate que agregué variables, saqué 2 lineas afuera del loop porque deben ir afuera si no quizás funcione igual pero es ineficiente y tarda de más, y agregué la fila del DataTable que coloca los totales ... Oremos que funcione ... Visual Basic no es mi lenguaje en absoluto y me parece feo pero (creo que) vi la forma de ayudar un poquito 

               Dim TotStock, TotSumar, TotRestar, TotResultado As Integer
               TotStock = TotSumar = TotRestar = TotResultado = 0
    
               Dim LINEA As DataGridViewRow
                For Each LINEA In Me.DataGridView2.Rows
                    CODIGO = CInt(LINEA.Cells(0).Value)
                    PRODUCTO = CStr(LINEA.Cells(1).Value)
                    PRESENTACION = CStr(LINEA.Cells(2).Value)
                    U_M = CStr(LINEA.Cells(3).Value)
                    PROVEEDOR = CStr(LINEA.Cells(4).Value)
                    STOCK = CDbl(LINEA.Cells(5).Value)
                    TotStock = TotStock + STOCK
                    SUMAR = Nothing
                    TotSumar = TotSumar + SUMAR;
                    RESTAR = Nothing
                    TotRestar = TotRestar + RESTAR
                    RESULTADO = Nothing
                    TotResultado = TotResultado + RESULTADO
    
                    MY_DataTable.Rows.Add(CODIGO, PRODUCTO, PRESENTACION, U_M, PROVEEDOR, STOCK, SUMAR, RESTAR, RESULTADO)
    
                Next
    
                MY_DataTable.Rows.Add(new object[] { "", "TOTALES", "", "", "", TotStock, TotSumar, TotRestar, TotResultado });           
     
                ME_DV_AUXILIAR = MY_DataTable.DefaultView
                Me.DataGridView1.DataSource = ME_DV_AUXILIAR
    

    Saludos


    domingo, 25 de julio de 2021 19:29

Todas las respuestas

  • Hola Reynaldo,

    Gracias por levantar tu consulta en los foros de MSDN.

    Eric Ruiz

    ____________________________

    Por favor recuerde "Marcar como respuesta" las respuestas que hayan resuelto su problema, es una forma común de reconocer a aquellos que han ayudado, y hace que sea más fácil para los otros visitantes encontrar la solución más tarde.

    Si tiene algún cumplido o reclamo sobre el soporte de MSDN siéntase en la libertad de contactar MSDNFSF@microsoft.com.

    jueves, 22 de julio de 2021 19:08
    Moderador
  • Hola Reynaldo

    Si vas a trabajar con el DataGridView enlazado a datos, podes cambiar tu consulta de SQL a la siguiente:

    select CAST(Id as varchar(30)), Nombre, Cantidad
    from Vehiculos
    union
    select 'Totales', '', sum(Cantidad)
    from Vehiculos

    Para mi te conviene más trabajar sin enlazar, y así sería más fácil agregar la fila de totales.

    Saludos

    Pablo



    jueves, 22 de julio de 2021 21:18
  • Hola buenos días, yo cargo el datagrid de la siguiente forma, primero cargo un datagridview2 con este código:

     Private Sub CargarInventario()
            Try
                Dim cnn As New SqlConnection(CS)
                Dim da As New SqlDataAdapter("SELECT * from dbo.MostrarProductos_ParaRellenarSurtidos", cnn)
                Dim ds As New DataSet
                da.Fill(ds)
                dv2.Table = ds.Tables(0)
                DataGridView2.DataSource = dv2
    
                cnn.Close()
            Catch ex As Exception
                FormMsgBoxError.Show(ex.Message, "Se produjo un error.")
            End Try
        End Sub


    posterior al cargar el form en el evento load hago lo siguiente:

     Private Sub FormCrearSurtidoMejorado_Load(sender As Object, e As EventArgs) Handles Me.Load
    
    
            Try
    
                lx = Me.Location.X
                ly = Me.Location.Y
                sw = Me.Size.Width
                sh = Me.Size.Height
                Me.Size = Screen.PrimaryScreen.WorkingArea.Size
                Me.Location = Screen.PrimaryScreen.WorkingArea.Location
    
                Call automatizarEntrada()
    
                Me.DataGridView2.Visible = False
    
                'Mostramo la marca
                Me.lblmarca_agua.Visible = True
                'Agregamos los eventos para el procedimiento GotfocusTexto
                AddHandler txtsearch.GotFocus, AddressOf GotfocusTexto
                ' Agregamos los eventos para el procedimiento LostfocusTexto
                AddHandler txtsearch.LostFocus, AddressOf LostfocusTexto
    
                Call CargarInventario()
    
                'THES ITEMS ARE OBTAIN ON THE LIST
                Dim CODIGO As Integer
                Dim PRODUCTO, PRESENTACION, U_M, PROVEEDOR As String
                Dim STOCK, SUMAR, RESTAR, RESULTADO As Double
    
                'THE NEXT ITEMS ARE OBTAIN ANOTHER PRCCESS
                MY_DataTable.Columns.Add("Código")
                MY_DataTable.Columns.Add("Producto")
                MY_DataTable.Columns.Add("Presentación")
                MY_DataTable.Columns.Add("U_M")
                MY_DataTable.Columns.Add("Proveedor")
                MY_DataTable.Columns.Add("Stock")
    
                MY_DataTable.Columns.Add("Sumar")
                MY_DataTable.Columns.Add("Restar")
                MY_DataTable.Columns.Add("Resultado")
    
                Dim LINEA As DataGridViewRow
                For Each LINEA In Me.DataGridView2.Rows
                    CODIGO = CInt(LINEA.Cells(0).Value)
                    PRODUCTO = CStr(LINEA.Cells(1).Value)
                    PRESENTACION = CStr(LINEA.Cells(2).Value)
                    U_M = CStr(LINEA.Cells(3).Value)
                    PROVEEDOR = CStr(LINEA.Cells(4).Value)
                    STOCK = CDbl(LINEA.Cells(5).Value)
                    SUMAR = Nothing
                    RESTAR = Nothing
                    RESULTADO = Nothing
    
                    MY_DataTable.Rows.Add(CODIGO, PRODUCTO, PRESENTACION, U_M, PROVEEDOR, STOCK, SUMAR, RESTAR, RESULTADO)
                    ME_DV_AUXILIAR = MY_DataTable.DefaultView
                    Me.DataGridView1.DataSource = ME_DV_AUXILIAR
    
                Next
    
                Call PersonalizarDGV1()
    
    
    
    
            Catch ex As Exception
                FormMsgBoxError.Show(ex.Message, "Se produjo un error.")
            End Try
    
    
        End Sub

    hasta ahi no necesito mostrar totales, pero cuando el usuario filtre ese datagridview1 es ahi donde necesito que me muestre la fila de totales.


    viernes, 23 de julio de 2021 16:06
  • Hola Reynaldo,

    Me horroriza Visual Basic, pero ... retoqué tu código, fijate que agregué variables, saqué 2 lineas afuera del loop porque deben ir afuera si no quizás funcione igual pero es ineficiente y tarda de más, y agregué la fila del DataTable que coloca los totales ... Oremos que funcione ... Visual Basic no es mi lenguaje en absoluto y me parece feo pero (creo que) vi la forma de ayudar un poquito 

               Dim TotStock, TotSumar, TotRestar, TotResultado As Integer
               TotStock = TotSumar = TotRestar = TotResultado = 0
    
               Dim LINEA As DataGridViewRow
                For Each LINEA In Me.DataGridView2.Rows
                    CODIGO = CInt(LINEA.Cells(0).Value)
                    PRODUCTO = CStr(LINEA.Cells(1).Value)
                    PRESENTACION = CStr(LINEA.Cells(2).Value)
                    U_M = CStr(LINEA.Cells(3).Value)
                    PROVEEDOR = CStr(LINEA.Cells(4).Value)
                    STOCK = CDbl(LINEA.Cells(5).Value)
                    TotStock = TotStock + STOCK
                    SUMAR = Nothing
                    TotSumar = TotSumar + SUMAR;
                    RESTAR = Nothing
                    TotRestar = TotRestar + RESTAR
                    RESULTADO = Nothing
                    TotResultado = TotResultado + RESULTADO
    
                    MY_DataTable.Rows.Add(CODIGO, PRODUCTO, PRESENTACION, U_M, PROVEEDOR, STOCK, SUMAR, RESTAR, RESULTADO)
    
                Next
    
                MY_DataTable.Rows.Add(new object[] { "", "TOTALES", "", "", "", TotStock, TotSumar, TotRestar, TotResultado });           
     
                ME_DV_AUXILIAR = MY_DataTable.DefaultView
                Me.DataGridView1.DataSource = ME_DV_AUXILIAR
    

    Saludos


    domingo, 25 de julio de 2021 19:29
  • Muchas gracias Tigre por tu apoyo, no me ha funcionado. no carga nada. 
    lunes, 26 de julio de 2021 16:40
  • Hola a todos, no he podido lograr agregar la fila de gran totales al final del datagridview, por lo tanto se me ha acabado el tiempo y he recurrido a una chapuzada para poder mostrar algo que satisfaga al cliente, coloque en la parte de abajo unos botones personalizados en totales 5 en estos coloco los totales los cuales capturo con una función que sumo las columnas del datagridview y pues los coloco de modo que capturo la posiciones de los encabezados del datagridview para que se vean alineados a las celdas y pues me ha quedado algo bien.

    Les comparto el resultado.

    Función para sumar las columnas:

      Public Sub sumarColumnas()
            Try
                Dim LINEA As DataGridViewRow : Dim toResultado As Double : Dim toSuma As Double : Dim toRestar As Double : Dim toStock As Double : Dim toItems As Integer
                For Each LINEA In Me.DataGridView1.Rows
                    toResultado = toResultado + LINEA.Cells(9).Value
                    toRestar = toRestar + LINEA.Cells(8).Value
                    toSuma = toSuma + LINEA.Cells(7).Value
                    toStock = toStock + LINEA.Cells(6).Value
    
                Next
    
                toItems = Me.DataGridView1.Rows.Count
                Me.BTN_ITEMS.Text = "Ítems: " + "" + CStr(toItems)
    
    
                Me.BTN_COLUMNA_RESULTADO.Text = toResultado
                Me.BTN_COLUMNA_RESULTADO.Text = Format(CType(Me.BTN_COLUMNA_RESULTADO.Text, Decimal), "#,##0.00")
    
                Me.BTN_COLUMNA_RESTAR.Text = toRestar
                Me.BTN_COLUMNA_RESTAR.Text = Format(CType(Me.BTN_COLUMNA_RESTAR.Text, Decimal), "#,##0.00")
    
                Me.BTN_COLUMNA_SUMAR.Text = toSuma
                Me.BTN_COLUMNA_SUMAR.Text = Format(CType(Me.BTN_COLUMNA_SUMAR.Text, Decimal), "#,##0.00")
    
    
                Me.BTN_COLUMNA_STOCK.Text = toStock
                Me.BTN_COLUMNA_STOCK.Text = Format(CType(Me.BTN_COLUMNA_STOCK.Text, Decimal), "#,##0.00")
    
    
            Catch expSQL As Exception
                MsgBox(expSQL.ToString, MsgBoxStyle.OkOnly, "SQL Exception")
            End Try
    
        End Sub

    Función para colocar los botones alineados a los encabezados del datagridview:

    Public Function posicionarTotasles()
    
    
            Call sumarColumnas()
    
            Dim rect_1 As Rectangle = DataGridView1.GetCellDisplayRectangle(9, -1, True)
            Me.BTN_COLUMNA_RESULTADO.Size = rect_1.Size
            BTN_COLUMNA_RESULTADO.Location = New Point(rect_1.Location.X + DataGridView1.Location.X, rect_1.Location.Y + DataGridView1.Location.Y)
    
            Dim rect_2 As Rectangle = DataGridView1.GetCellDisplayRectangle(8, -1, True)
            Me.BTN_COLUMNA_RESTAR.Size = rect_2.Size
            BTN_COLUMNA_RESTAR.Location = New Point(rect_2.Location.X + DataGridView1.Location.X, rect_2.Location.Y + DataGridView1.Location.Y)
    
            Dim rect_3 As Rectangle = DataGridView1.GetCellDisplayRectangle(7, -1, True)
            Me.BTN_COLUMNA_SUMAR.Size = rect_3.Size
            BTN_COLUMNA_SUMAR.Location = New Point(rect_3.Location.X + DataGridView1.Location.X, rect_3.Location.Y + DataGridView1.Location.Y)
    
            Dim rect_4 As Rectangle = DataGridView1.GetCellDisplayRectangle(6, -1, True)
            Me.BTN_COLUMNA_STOCK.Size = rect_4.Size
            BTN_COLUMNA_STOCK.Location = New Point(rect_4.Location.X + DataGridView1.Location.X, rect_4.Location.Y + DataGridView1.Location.Y)
    
            Dim rect_5 As Rectangle = DataGridView1.GetCellDisplayRectangle(5, -1, True)
            Me.BTN_ITEMS.Size = rect_5.Size
            BTN_ITEMS.Location = New Point(rect_5.Location.X + DataGridView1.Location.X, rect_5.Location.Y + DataGridView1.Location.Y)
    
    
            Me.BTN_COLUMNA_RESULTADO.Visible = True
            Me.BTN_COLUMNA_RESTAR.Visible = True
            Me.BTN_COLUMNA_SUMAR.Visible = True
            Me.BTN_COLUMNA_STOCK.Visible = True
            Me.BTN_TEXT_TOTALES.Visible = True
            Me.BTN_ITEMS.Visible = True
    
    
    
        End Function

    Resultado:

    Muchas gracias a todos.

    Saludos.

     
    lunes, 26 de julio de 2021 18:03