3

I need to format the labels of the time axis in a MSChart like "CW21", "CW22", ... I am struggling for a while and could not find any solution yet.

  1. There is a LabelStyle.Format property but this does not support (AFAIK) calendar weeks. It uses the DateTime formatting strings. Is there a way to introduce a custom formatter?

  2. In the framework I found the Calendar.GetWeekOfYear method, which would provide me with the right week number. Now the question is how to bring these together?

Is there any good strategy to setup one's own labels on the axis in a generic manner? (without knowing in advance the min/max points of the axis)

jdehaan
  • 19,700
  • 6
  • 57
  • 97

1 Answers1

8

Yes, you can use the Chart.FormatNumber event e.g.:

private void FillChart()
{
    // register the format event
    this.chart1.FormatNumber += new EventHandler<FormatNumberEventArgs>(chart1_FormatNumber);

    // fill the data table with values
    DataTable dt = new DataTable();
    dt.Columns.Add("X", typeof(DateTime));
    dt.Columns.Add("Y", typeof(double));

    dt.Rows.Add(DateTime.Today.AddDays(1), 10);
    dt.Rows.Add(DateTime.Today.AddDays(8), 30);
    dt.Rows.Add(DateTime.Today.AddDays(15), 10);
    dt.Rows.Add(DateTime.Today.AddDays(21), 20);
    dt.Rows.Add(DateTime.Today.AddDays(25), 40);
    dt.Rows.Add(DateTime.Today.AddDays(31), 25);

    // bind the data table to chart
    this.chart1.Series.Clear();

    var series = this.chart1.Series.Add("Series 1");
    series.XValueMember = "X";
    series.YValueMembers = "Y";

    series.ChartType = SeriesChartType.Line;
    this.chart1.DataSource = dt;
    this.chart1.DataBind();

    // set a custom format to recognize the AxisX label in the event handler
    this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "CustomAxisXFormat"; 

}

void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
{
    if (e.ElementType == ChartElementType.AxisLabels &&
        e.Format == "CustomAxisXFormat")
    {
        if (e.ValueType == ChartValueType.DateTime)
        {
            var currentCalendar = CultureInfo.CurrentCulture.Calendar;
            e.LocalizedValue = "CW" +
                currentCalendar.GetWeekOfYear(DateTime.FromOADate(e.Value),
                System.Globalization.CalendarWeekRule.FirstDay,
                CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
        }
    }
}

Here's the result:

enter image description here

digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • Thanks man! I suspected events at axis class level (there were none) but I did not look at the chart class!! You saved my day! – jdehaan Aug 10 '11 at 12:12