create calculatedfield in Pivot Grid

3 Answers 131 Views
PivotGrid and PivotFieldList
Informatica
Top achievements
Rank 1
Iron
Informatica asked on 11 Apr 2022, 07:05 AM | edited on 11 Apr 2022, 07:08 AM

Hello,

 

it doesn't work for me. I don't know why...

 

My code try to build the code with parameters in a table, later I try to add calculatedfield, but I can't see the calculated field in the list... I think is the part of "The important part here is to add the custom field before setting the ItemsSource property", but I don't know how to manage it with my code...

My code:

 

  Try



            Me.RadPivotGrid1.AggregatesPosition = PivotAxis.Columns

            'MsgBox(numcubo)

            'cierro conexión
            conexion.Close()
            'abro conexión
            conexion.Open()
            'borro y cojo el detalle de apuntes del mes
            strSQL = "SELECT * FROM  [Profesionales].[dbo].[COSTES_cubos] where trim(cubo)=trim('" & numcubo & "') order by cubo, tipo, orden "

            oCommand = New SqlCommand(strSQL, conexion)
            oCommand.CommandTimeout = 0

            oCommand.CommandText = strSQL
            dataResult = oCommand.ExecuteReader()

            If dataResult.HasRows Then
                Do While dataResult.Read()

                    'sql
                    If dataResult.Item("tipo") = 1 Then

                        'strSQL = Me.Ini_SQL
                        strSQL = dataResult.Item("texto").ToString.Trim()
                        oCommand2 = New SqlCommand(strSQL, conexion)
                        oCommand2.CommandText = strSQL
                        oCommand2.CommandTimeout = 0
                        Cube_DataAdapter2 = New SqlDataAdapter(oCommand2)
                        Cube_DataSet2 = New DataSet()
                        Cube_DataAdapter2.Fill(Cube_DataSet2, "SQL")

                    End If

                    'fila
                    If dataResult.Item("tipo") = 2 Then

                        'Asigno valores
                        pivotRow = New PropertyGroupDescription()

                        pivotRow.PropertyName = dataResult.Item("texto").ToString.Trim()
                        pivotRow.CustomName = dataResult.Item("alias").ToString.Trim()

                        Me.RadPivotGrid1.ColumnGroupDescriptions.Add(pivotRow)

                    End If

                    'columna
                    If dataResult.Item("tipo") = 3 Then


                        'Asigno valores
                        pivotCol = New PropertyGroupDescription()
                        '  Dim pivotC = New PropertyAggregateDescription()
                        pivotCol.PropertyName = dataResult.Item("texto").ToString.Trim()
                        pivotCol.CustomName = dataResult.Item("alias").ToString.Trim()

                        Me.RadPivotGrid1.RowGroupDescriptions.Add(pivotCol)

                    End If

                    'datos
                    If dataResult.Item("tipo") = 4 Then

                        'Asigno valores
                        pivotVal = New PropertyAggregateDescription()
                        pivotVal.PropertyName = dataResult.Item("texto").ToString.Trim()
                        pivotVal.CustomName = dataResult.Item("alias").ToString.Trim()
                        pivotVal.StringFormat = dataResult.Item("formato").ToString.Trim()
                        pivotVal.AggregateFunction = AggregateFunctions.Sum

                        Me.RadPivotGrid1.AggregateDescriptions.Add(pivotVal)
                    End If

                    'filtros
                    If dataResult.Item("tipo") = 5 Then

                        Dim description As New PropertyFilterDescription()
                        Dim condition As New ComparisonCondition()
                        condition.Condition = Telerik.Pivot.Core.Filtering.Comparison.Equals
                        'condition.Than = "UK"
                        description.PropertyName = dataResult.Item("texto").ToString.Trim()
                        'description.Condition = condition
                        description.CustomName = dataResult.Item("alias").ToString.Trim()
                        Me.RadPivotGrid1.FilterDescriptions.Add(description)

                    End If



                    'orden
                    If dataResult.Item("tipo") = 6 Then


                        Dim propGroupDescription As PropertyGroupDescription = DirectCast(Me.RadPivotGrid1.RowGroupDescriptions(0), PropertyGroupDescription)
                        If dataResult.Item("sort").ToString.Trim() = "Ascending" Then
                            propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Ascending
                        Else
                            propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Descending
                        End If
                        propGroupDescription.GroupComparer = New GrandTotalComparer() With {
         .AggregateIndex = dataResult.Item("orden")
        }
                            Me.RadPivotGrid1.ReloadData()
                        End If

                Loop
            End If








            Me.RadPivotGrid1.DataSource = Cube_DataSet2
            Me.RadPivotGrid1.DataMember = "SQL"


           Using RadPivotGrid1.PivotGridElement.DeferRefresh()
                Dim calculatedField As New CommissionCalculatedField()
                calculatedField.Name = "Commission"
                DirectCast(Me.RadPivotGrid1.DataProvider, LocalDataSourceProvider).CalculatedFields.Add(calculatedField)
            End Using


            ''Cargo layout por defecto
            'If Me.Ini_Layout <> "" Then
            '    Me.RadPivotGrid1.LoadLayout(Me.Ini_Layout)
            'End If
            'Cargo grafico
            Me.RadChartView.DataSource = Me.RadPivotGrid1





            Dim verticalAxis As New LinearAxis()
            'verticalAxis.AxisType = AxisType.Second
            Dim horizontalAxis As New CategoricalAxis()
            horizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine
            Me.RadChartView.Area.Axes.Add(horizontalAxis)
            Me.RadChartView.Area.Axes.Add(verticalAxis)
            Me.RadChartView.ChartElement.LegendElement.Visibility = Telerik.WinControls.ElementVisibility.Visible
            'Me.RadChartView.ChartElement.LegendPosition = LegendPosition.Right
            Me.RadChartView.ChartElement.LegendElement.Alignment = System.Drawing.ContentAlignment.TopCenter
            'Configuracion totales grafico
            Me.RadPivotGrid1.ChartDataProvider.IncludeRowSubTotals = False
            Me.RadPivotGrid1.ChartDataProvider.IncludeColumnSubTotals = False
            Me.RadPivotGrid1.ChartDataProvider.IncludeRowGrandTotals = False
            Me.RadPivotGrid1.ChartDataProvider.IncludeColumnGrandTotals = False
            'Oculto grafico
            Me.SplitContainer2.Panel2Collapsed = True
            Me.SplitContainer1.Panel1Collapsed = True
            Me.RadChartView.Title = Me.Titulo



            'cierro conexión
            conexion.Close()

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)

        End Try

 

and the class:

 


    Public Class CommissionCalculatedField
        Inherits CalculatedField
        Private extendPriceField As RequiredField
        Public Sub New()
            Me.Name = "Commission"
            Me.extendPriceField = RequiredField.ForProperty("importe")
        End Sub
        Protected Overrides Function RequiredFields() As IEnumerable(Of RequiredField)
            Return New List(Of RequiredField) From {extendPriceField}
        End Function
        Protected Overrides Function CalculateValue(aggregateValues As IAggregateValues) As AggregateValue
            Dim aggregateValue = aggregateValues.GetAggregateValue(Me.extendPriceField)
            If aggregateValue.IsError() Then
                Return aggregateValue
            End If
            Dim extendedPrice As Double = aggregateValue.ConvertOrDefault(Of Double)()

            Return New DoubleAggregateValue(extendedPrice * 0.1)

            Return Nothing
        End Function
    End Class                

3 Answers, 1 is accepted

Sort by
0
Accepted
Hristo
Telerik team
answered on 18 Apr 2022, 09:18 AM

Hello,

Thanks for sending me the form files. I am not able to build them as they contain application specific logic, still I think I saw what might be causing the issue. 

The problem seems to be that you first create a LocalDataSourceProvider and you set it to the pivot's DataSource property, just before adding the calculated field: 

'Añade campo calculado
Me.RadPivotGrid1.DataProvider = provider

Using RadPivotGrid1.PivotGridElement.DeferRefresh()
    Dim calculatedField As New CommissionCalculatedField()
    calculatedField.Name = "Commission"

    DirectCast(Me.RadPivotGrid1.DataProvider, LocalDataSourceProvider).CalculatedFields.Add(calculatedField)
End Using

The above setup is correct. However, later you directly set the DataSource property of the RadPivotGrid. This causes a new DataProvider to be instatitated and you will loose the calculated field. Instead of working with the data source property of the control, you can set the ItemsSource property of the data provider you already have. Close to the end of the Load_Cube method, you can change it like this: 

Me.provider.ItemsSource = Cube_DataSet2.Tables("SQL")
'Me.RadPivotGrid1.DataSource = Cube_DataSet2
'Me.RadPivotGrid1.DataMember = "SQL"

I hope that this approach would work in your actual project.

Let me know if you have other questions.

Regards,
Hristo
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Informatica
Top achievements
Rank 1
Iron
commented on 18 Apr 2022, 12:22 PM

It´s working! Thank you!
0
Hristo
Telerik team
answered on 13 Apr 2022, 11:05 AM

Hello,

The calculated field needs to be added before setting the data source so that it be considered when extracting the data and creating the field list. This is mentioned in our documentation here: Calculated Fields | RadPivotGrid | Telerik UI for WinForms.

In your code snippet I see that you first set the data source of the pivot and the you add the calculated field. Can you please try first adding the calculated field and then setting the DataSource property? Please also note that in order to see some calculation according to this custom field you will need to add an aggregate for it. Something similar to: 

Dim calculatedAggregate As New CalculatedAggregateDescription()
calculatedAggregate.CalculatedFieldName = "Commission"
DirectCast(RadPivotGrid1.DataProvider, LocalDataSourceProvider).AggregateDescriptions.Add(calculatedAggregate)

I am also attaching my test project demonstrating a sample setup. In case you keep experiencing the issue please open up a support ticket and send us a repro so that we can further investigate.

I hope this will help. Let me know if you have other questions.

Regards,
Hristo
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

0
Informatica
Top achievements
Rank 1
Iron
answered on 18 Apr 2022, 06:03 AM

Thank you for the answer and example, but the field doesn't appear in the list.

I have add the bellow at the begining and works but the field doesn't appear in the list:

If dataResult.HasRows Then


                'Añade campo calculado
                Me.RadPivotGrid1.DataProvider = provider

                Using RadPivotGrid1.PivotGridElement.DeferRefresh()
                    Dim calculatedField As New CommissionCalculatedField()
                    calculatedField.Name = "Commission"

                    DirectCast(Me.RadPivotGrid1.DataProvider, LocalDataSourceProvider).CalculatedFields.Add(calculatedField)
                End Using

                Dim calculatedAggregate As New CalculatedAggregateDescription()
                calculatedAggregate.CalculatedFieldName = "Commission"
                DirectCast(RadPivotGrid1.DataProvider, LocalDataSourceProvider).AggregateDescriptions.Add(calculatedAggregate)

    Do While dataResult.Read()

I have add the code.

I think that I quit the calculated field of the list when I load the sql datasource.

best regards,

Tags
PivotGrid and PivotFieldList
Asked by
Informatica
Top achievements
Rank 1
Iron
Answers by
Hristo
Telerik team
Informatica
Top achievements
Rank 1
Iron
Share this question
or