Search code examples
c#winformschartsmschart

Get custom label from clicked column of MS Chart control (WinForm)


I'm using MS Chart control in my WinForm project: enter image description here

I want write some code to get clicked column's label, e.g if user clicked A column it returns "A [ EAF/LF ]" and if user clicks B column it returns "B [ VD/VOD ]". So I wrote following code to find clicked column in chart and show the custom defined label:

private void chart_MouseDown(object sender, MouseEventArgs e)
{
    var result = chart.HitTest(e.X, e.Y);

    if (result.ChartElementType == ChartElementType.DataPoint)
    {
       var selectedColumn = chart.Series[0].Points[result.PointIndex];
       var customLabel = selectedColumn.AxisLabel + "[ "
                         result.Axis.CustomLabels[result.PointIndex] + " ]";
       // other codes
     }
}   

But when run the code the result.Axis is null. Does anyone know where is the problem?


Solution

  • The Axis property has value only if the object returned by the HitTest is associated with an axis. For example, a tick mark or stripline. For the DataPoint object it returns null.

    To get the CustomLabels you could use the below code.

    chart.ChartAreas[chart.Series[0].CharArea].AxisX.CustomLabels[result.PointIndex];