steve cook steve cook - 1 month ago 26
C# Question

Auto format DateTime axis for MS chart control?

I'm using the MS chart control to display a time series. Points are added to the series over time, and the user can zoom in/out using the normal built-in controls.

The question is, how can I set it up so that the X-axis labels automatically show a format that's appropriate for the time range being displayed?

For example, when the time range displayed on the chart is < 1 hour, I'd want to set it to display HH:mm:ss:

ChartAreas[0].AxisX.LabelStyle.Format ="HH:mm:ss";


But if I zoom out on the same chart to show 6 days of data, I'd want it to display just the date:

ChartAreas[0].AxisX.LabelStyle.Format ="dd/MM/yy";


Is there any built-in functionality to do this?

Answer

You can hook into the Chart.AxisViewChanged event (assuming you're using the built-in zooming functionality of the chart), and set the format based on the axis range:

private void Chart_AxisViewChanged(object sender, ViewEventArgs e)
{
    DateTime range = ChartAreas[0].AxisX.ScaleView.ViewMaximum - ChartAreas[0].AxisX.ScaleView.ViewMinimum;
    if (range > 6 days)
    {
        ChartAreas[0].AxisX.LabelStyle.Format = "dd/MM/yy";
    }
    else
    {
        ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
    }
}

You can of course make that if statement more complicated to handle more cases as desired.