简体   繁体   中英

c# bind winforms chart to list of objects

I have a list of objects defined like this:

public class ChartData
{
    public int New
    {
        get;
        set;
    }

    public int Closed
    {
        get;
        set;
    }

    public int Canceled
    {
        get;
        set;
    }
}

How can I bind a winforms-chart (bar-chart type) to a List<ChartData> ? I need to have a series for each property in the object (ie, I will have 3 series) and for each point in the chart, I want to see the values for all 3 properties in the object.

I managed to programatically add the series (they're visible in the chart), but when I try to set the data source, it crashes:

        List<ChartData> data = new List<ChartData>();
        // fill with random int values
        chart.DataSource = data;

        chart.Series.Add("New").XValueMember = "New";
        chart.Series["New"].ChartType = SeriesChartType.Bar;
        chart.Series["New"].XValueType = ChartValueType.Int32;
        chart.Series["New"].YValueType = ChartValueType.Int32;

        chart.Series.Add("Canceled").XValueMember = "Canceled";
        chart.Series["Canceled"].ChartType = SeriesChartType.Bar;
        chart.Series["Canceled"].XValueType = ChartValueType.Int32;
        chart.Series["Canceled"].YValueType = ChartValueType.Int32;

        chart.Series.Add("Closed").XValueMember = "Closed";
        chart.Series["Closed"].ChartType = SeriesChartType.Bar;
        chart.Series["Closed"].XValueType = ChartValueType.Int32;
        chart.Series["Closed"].YValueType = ChartValueType.Int32;

        chart.DataBind();

with an System.ArgumentOutOfRangeException , saying that Data points insertion error. Only 1 Y values can be set for this data series. Data points insertion error. Only 1 Y values can be set for this data series. ...

Any help/hint?

Replace XValueMember with YValueMembers :

        chart.Series.Add("New").YValueMembers = "New";
        chart.Series["New"].ChartType = SeriesChartType.Bar;
        chart.Series["New"].XValueType = ChartValueType.Int32;
        chart.Series["New"].YValueType = ChartValueType.Int32;

        chart.Series.Add("Canceled").YValueMembers = "Canceled";
        chart.Series["Canceled"].ChartType = SeriesChartType.Bar;
        chart.Series["Canceled"].XValueType = ChartValueType.Int32;
        chart.Series["Canceled"].YValueType = ChartValueType.Int32;

        chart.Series.Add("Closed").YValueMembers = "Closed";
        chart.Series["Closed"].ChartType = SeriesChartType.Bar;
        chart.Series["Closed"].XValueType = ChartValueType.Int32;
        chart.Series["Closed"].YValueType = ChartValueType.Int32;

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM