Search code examples
asp.netvb.netchartspie-chartmschart

Legend Items appearing n times more than the number of items in Series in ASP.Net Pie Chart using MS Chart Control


I am using MS Chart Control in ASP.Net using VB.Net. The chart type is Pie. I am facing a weird problem where the number of items displayed in the legend is square of the number of Series present. This means if I have 2 series added to the pie chart, 4 items are displayed in legend and if I have 7 series added to the pie chart, 49 items appear in the legend. The 1st set of 7 items displaying the correct data and the others just displaying 0.

Here is the markup of my chart control in ASPX -

 <asp:Chart runat="server" ID="chartX" CssClass="chart" Width="420px" Height="500px" ImageType="Jpeg">
    <Series></Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1"></asp:ChartArea>
    </ChartAreas>
    <Legends>
        <asp:Legend Docking="Bottom" Alignment="Center" Font="Calibri"></asp:Legend>
    </Legends>
 </asp:Chart>

Here is the code to populate chart control in ASPX.vb -

Dim table As DataTable = PopulateData()
Dim dv As DataView = New DataView(table, "Count > 0", "", DataViewRowState.OriginalRows)

For Each r As DataRow In dv.ToTable().Rows

            Dim series As String = r("Name").ToString()
            chartX.Series.Add(series)
            chartX.Series(series).ChartType = DataVisualization.Charting.SeriesChartType.Pie
            chartX.Series(series).XValueMember = "Name"
            chartX.Series(series).YValueMembers = "Count"
            chartX.ChartAreas(0).Area3DStyle.Enable3D = True
            chartX.Series(series).Label = "#VALX" & Environment.NewLine & "(#PERCENT)"
            chartX.Series(series)("PieLabelStyle") = "Disabled"
    Next
    chartX.DataSource = dv
    chartX.DataBind()

Hoping for any answers.


Solution

  • If I'm not mistaken, you are adding a new series for each row in you table. Instead you should be adding the series once for the table and then binding your data.

    You do not need to iterate through all rows when setting up your graph. Do it only once binding to the table. I never touch VB, but it should looks something like this

    Dim table As DataTable = PopulateData()
    Dim dv As DataView = New DataView(table, "Count > 0", "", DataViewRowState.OriginalRows)
    ' setup just once
    Dim series As String = "Series Name"
    chartX.Series.Add(series)
    chartX.Series(series).ChartType = DataVisualization.Charting.SeriesChartType.Pie
    chartX.Series(series).XValueMember = "Name"
    chartX.Series(series).YValueMembers = "Count"
    chartX.ChartAreas(0).Area3DStyle.Enable3D = True
    chartX.Series(series).Label = "#VALX" & Environment.NewLine & "(#PERCENT)"
    chartX.Series(series)("PieLabelStyle") = "Disabled"
    ' bind to the entire set
    chartX.DataSource = dv
    chartX.DataBind()