Skip to main content Skip to footer

How to set maximum count of legends visible in WinForms

Issue:

When using Charts in Spread for WinForms, there can be scenarios where there are many series in the charts and hence, the legends populate the chart view.

In such scenarios, a requirement can be to hide legends or define the maximum count of legends to show, without removing the series from the chart. This way the developer can make space in the chart view without reducing the information presented by the chart.

Therefore, this article shows how to restrict the number of legends visible without hiding the corresponding series.

Resolution:

In Spread, the LegendArea and the Series classes have a ‘LegendAreaId’ property. A given series displays its legend in LegendArea with a matching LegendAreaId.

1. If the need is to define a max count of visible legends: Set a series' LegendAreaId to a value that does not match any legend area's LegendAreaId. Doing this for all series with index’s greater than the max legend count value will restrict any further legends to appear.

int maxLegendCount = 2;
FarPoint.Win.Chart.PlotArea plotArea = fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0];
for (int i = maxLegendCount;  i < plotArea.Series.Count; i++)
{
     plotArea.Series[i].LegendAreaId = new Random().Next(10,1000);
}

2. If the need is to hide the legend of a specific series only: Just access the specific series from the Series collection and set its LegendAreaId to a value that does not match any legend area's LegendAreaId.

FarPoint.Win.Chart.PlotArea plotArea = fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0];
plotArea.Series[1].LegendAreaId = new Random().Next(10, 1000);

Tags:

Ruchir Agarwal