Search code examples
c#.netwinformschartsmschart

How to sort a bar chart without changing the query?


I searched and tried a lot of different things, but I can't find a way to sort my column chart. We want to have the largest quantity at the top instead of at the bottom.

I can't change the query, but I need to sort the chart.

enter image description here

I tried the following:

ColumnChartMachine.Series(0).Sort(PointSortOrder.Descending, "Y")

and

 ColumnChartMachine.DataManipulator.Sort(PointSortOrder.Descending, "Y", "SeriesMachines")

Where I changed the Y to different values, and Ascending / Descending, just to see if it would do something, but no luck.

Any idea?


Solution

  • I can't change the query, but I need to sort the chart.

    You don't need to change the query, you should be able to use either of the following options:

    1. Sort data on the data source (no matter it's a DataTable or a List<T>, without changing your query, you can sort the result, on client).
    2. Sort chart points after calling DataBind

    Example

    Assuming you have data in a DataTable or a List<T>, like this:

    var table = new DataTable();
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Value", typeof(int));
    table.Rows.Add("FIT programmatiestation", 1);
    table.Rows.Add("Atlas 1N36", 1);
    table.Rows.Add("anilox cleaner", 1);
    table.Rows.Add("Nietjespistool", 1);
    table.Rows.Add("MORLOCK", 2);
    table.Rows.Add("MA 2200 4k!", 2);
    table.Rows.Add("Catena klein 2E21", 2);
    table.Rows.Add("Automatische kokerslitter 76 mm", 2);
    table.Rows.Add("ROP", 2);
    table.Rows.Add("RDC 1", 4);
    myChart.Series[0].ChartType =
        System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
    myChart.ChartAreas[0].AxisX.Interval = 1;
    

    Option 1 - Sort data source:

    myChart.DataSource = new DataView(table, "", "Value ASC", DataViewRowState.CurrentRows);
    myChart.Series[0].XValueMember = "Name";
    myChart.Series[0].YValueMembers = "Value";
    myChart.DataBind();
    

    Option 2 - Sort chart after calling DataBind:

    myChart.DataSource = table;
    myChart.Series[0].XValueMember = "Name";
    myChart.Series[0].YValueMembers = "Value";
    myChart.DataBind();
    myChart.Series[0].Sort(
        System.Windows.Forms.DataVisualization.Charting.PointSortOrder.Ascending);
    

    Both generate expected result:

    enter image description here