Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I was asked to put a number of graphics together for the office, and the "client" has a problem with the rectangles used within the chart's legend.

After doing some "research", I came across this MS document:
Chart.CustomizeLegend Event (System.Web.UI.DataVisualization.Charting)[^]

Which supposedly tells us how to "customize the chart legend items".

Despite my attempts, I cannot seem to affect said items at all.

What I have tried:

Markup:
<asp:Chart ID="PieChart" runat="server" Width="365px" OnCustomizeLegend="PieChart_CustomizeLegend">...

Code Behind:
protected void PieChart_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
{
    foreach (LegendItem lgItem in e.LegendItems)
    {
        lgItem.MarkerStyle = MarkerStyle.Diamond;
    }
}


Would you happen to know what is it that I am missing?

Thanks for your input.
Posted
Updated 10-May-18 10:44am
v2

1 solution

Hi there,

Please forgive me for not giving you all more time to come up with some ideas; here after, I'll explain what I did to get what I needed and leave all a question I was not able to find anything about.

All in all, customizing legend items was not as straight forward as I expected. I had to take the following steps:

1) Chart's legend has to be set to : LegendItemOrder="SameAsSeriesOrder", otherwise the result is all unorganized.

2) Modified the CustomizeLegend event as follows:
protected void PieChart_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
        {
            foreach (LegendItem lgItem in e.LegendItems)
            {
                if (!string.IsNullOrEmpty(lgItem.Name))
                {
                    LegendItem cstItem = new LegendItem();
                    cstItem.ImageStyle = LegendImageStyle.Marker;
                    cstItem.MarkerColor = lgItem.Color;
                    cstItem.Name = lgItem.Name;
                    cstItem.MarkerStyle = MarkerStyle.Diamond;
                    cstItem.MarkerSize = 15;
                    ((Chart)sender).Legends[0].CustomItems.Add(cstItem);
                }
            }
           
            ((Chart)sender).Series[0].IsVisibleInLegend = false;

            ((Chart)sender).CustomizeLegend -= PieChart_CustomizeLegend;
        }

Note that set the series IsVisibleInLegend property inside the event and not in the markup. If done in there, nothing will be drawn in the legend.

Moreover, I noticed that, somehow I cannot explain, the CustomizeLegend event was begin fired three times, giving undesired results, thus the un-subscription.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900