Search code examples
c#chartsmschart

How Can Alter X Axis Values In MSChart toName of Months


I want to alter chart X Axis values to show name of Months

Ex : 1 => January , 2 => February , etc.

        DataTable dt = new DataTable();
        SqlCommand s = new SqlCommand("ReportMonthly", SCon);
        s.CommandType = CommandType.StoredProcedure;
        s.Parameters.AddWithValue("@Year", Year);
        SCon.Open();
        SqlDataReader dr = s.ExecuteReader();
        dt.Load(dr);
        chtWRMonthly.DataSource = dt;
        chtWRMonthly.Series["Sold"].XValueMember = "Month";
        chtWRMonthly.Series["sRemaining"].XValueMember = "Month";
        chtWRMonthly.Series["Bought"].XValueMember = "Month";
        chtWRMonthly.Series["bRemaining"].XValueMember = "Month";
        chtWRMonthly.Series["Sold"].YValueMembers = "sTAccount";
        chtWRMonthly.Series["sRemaining"].YValueMembers = "sRemaining";
        chtWRMonthly.Series["Bought"].YValueMembers = "bTAccount";
        chtWRMonthly.Series["bRemaining"].YValueMembers = "bRemaining";
        SCon.Close();

and how can fix name of Months in the chart and then set their values ?

Example:

enter image description here


Solution

  • Unfortunately MSChart doesn't allow any real expressions, so I don't see how you could translate the integers to months directly.

    There are various workarounds but which you prefer will depend on you..

    1) modify the DataSource to bring back DateTimesor..

    2) ..to bring back the month strings.

    The latter will prevent you from working with the x-values.

    3) Modify the DataTable to contain DateTimes ; this must happen after each retrieval.

    4) replace the Axis.Labels altogether by CustomLabels.


    Here is an example of workaround #3: It adds a new column ('dateX') to the table and fills it with dates calculated from DateTime.Now.Date plus the integer in a column 'c1'. The y-values are in a column 'c2'.

    Of course you should use a suitable starting DateTime value, not the present date!

    Note that you need to tell the databinding about the type of the XValueMember and maybe also of the IntervalType!

    Finally you can format the new column to show the localized (German) month names..:

    if (!DT.Columns.Contains("dateX")) DT.Columns.Add("dateX", typeof(DateTime));
    
    foreach (DataRow row in DT.Rows)
        row.SetField<DateTime>("dateX", DateTime.Now.Date.AddMonths(row.Field<int>("c1")));
    
    
    Series s = chart1.Series[0];
    s.XValueMember = "dateX";
    s.XValueType = ChartValueType.DateTime;
    s.YValueMembers = "c2";
    
    chart1.DataSource = DT;
    chart1.DataBind();
    
    Axis ax = chart1.ChartAreas[0].AxisX;
    ax.LabelStyle.Format = "MMMM" ;
    ax.IntervalType = DateTimeIntervalType.Months;
    ax.Interval = 1;
    

    enter image description here