3

I am using the System.Windows.Forms.DataVisualization.Charting.Chart class to draw a chart with some data.

Now I want to suppress the automatic generation of entries within the legend and replace them with custom items. I have already found the way to add custom items but no way of suppressing the autogeneration.

My Code:

var legend = new Legend();
legend.LegendStyle = LegendStyle.Table;
legend.TableStyle = LegendTableStyle.Wide;
legend.IsEquallySpacedItems = true;
legend.IsTextAutoFit = true;
legend.BackColor = Color.White;
legend.Font = new Font(Config.FontFamily, 9);
legend.Docking = Docking.Bottom;
legend.Alignment = StringAlignment.Center;

legend.CustomItems.Add(new LegendItem("test", Color.Green, string.Empty));

ch.Legends.Add(legend);

Has anyone done something like this before?

Jan P.
  • 3,261
  • 19
  • 26
  • Can't you go to the property window, click the Legends... entry and select Remove for the default Legend? – Steve Wellens Sep 26 '12 at 13:45
  • The legend is ALLWAYS autogenerated by the added `Series`... this is what I want to suppress. – Jan P. Sep 26 '12 at 13:49
  • I deleted the existing default legend and then added a new series dynamically. No legend was created. Series MySeries = new Series(); MySeries.Points.Add(new DataPoint(5, 5)); MySeries.Points.Add(new DataPoint(5, 3)); MySeries.Points.Add(new DataPoint(4, 2)); this.chart1.Series.Add(MySeries); – Steve Wellens Sep 26 '12 at 13:54
  • Yeah... but I want a legend to displayed but filled with custom set names, like `legend.CustomItems.Add(new LegendItem("test", Color.Green, string.Empty));` – Jan P. Sep 26 '12 at 13:57

3 Answers3

3

Try doing it in this event:

private void chart1_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
{
    e.LegendItems.Clear();
    // new stuff
}
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
2

Go to the Series collection in the chart properties, and find the IsVisibleInLegend property and set it to false

DIF
  • 2,470
  • 6
  • 35
  • 49
Graham
  • 799
  • 2
  • 5
  • 14
1

I know this is old but wanted to post this here in case someone wants a slightly different way to go about it, this is based off of Steve Wellens answer but instead of adding the items in the event it just removes the non custom ones.

    protected void chartarea1_CustomizeLegend(object sender, System.Web.UI.DataVisualization.Charting.CustomizeLegendEventArgs e)
    {
        int customItems = ((Chart)sender).Legends[0].CustomItems.Count();
        if (customItems>0)
        {
            int numberOfAutoItems = e.LegendItems.Count()-customItems;
            for (int i = 0; i < numberOfAutoItems; i++)
            {
                e.LegendItems.RemoveAt(0);
            }
        }

    }
RustyH
  • 473
  • 7
  • 22