Search code examples
c#mschart

MSChart Customlabel reference not persisting


Please bear with my explanation as the code is on a computer I can't copy from.

I am using MSChart and CustomLabels with C#. I have a tree type list of another object each of which has a custom label as part of the class. example:

public class item
{
   public CustomLabel label = new CustomLabel();
   public List<item> children = new List<item>();
}

I setup the labels within these classes and then I push them into the YAxis (chartArea) example:

item.label.text = "some text";
chartArea.YAxis.CustomLabels.Add(item.label);

Further in the code I need to change the text of the label so I access my class label (verified the class was the same)

item.label.text = "new text";

but when I check the CustomLabels List the text value is still the old value

(chartArea.YAxis.CustomLabels[0].Text == "some text")

I do not understand why this is happening. I thought Instantiated objects were references. therefore should the text be "new text";

I have collapsible labels with is why I need to do it this way. Please help me understand.


Solution

  • Yes they are objects, but when adding them you are not simply adding them as a reference but they seem to get copied into the chart.

    (Hard to tell, as the sources for MSChart don't seem to be around.)

    So: You need to either re-assign the CustomLabels or change their properties in place.

    No need to add them again, just assign them again. For this you need to keep track of the labels you have. With only one this is simple:

    chart.ChartAreas[0].AxisX.CustomLabels[0] = yourItem.Label;
    

    To change the Text in place:

    chart.ChartAreas[0].AxisX.CustomLabels[0].Text = yourItem.Label.Text;
    

    This behaviour is different from, say, DataPoints. There you can keep a reference, change the values and it will show..

    Update:

    Out of curiosity I did the same test for all other ChartElement types I could think of, namely Annotations, ChartAreas, Legends, Series, Titles, LegendCellColumns and DataPoints. As it turns out they all are properly referenced and only references to CustomLabels are broken when you Add them.

    Looking into the CustomLabelsCollection Class I see not reason for this behaviour..

    Here are the before and after looks of the little test:

    enter image description here enter image description here