Romy
Romy

Reputation: 407

Set up a chart to draw points dynamically from a Class List

So i have a Class List <Entry> which looks like this:

namespace WindowsFormsApplication4.Models
{
    public class Entry
    {
        public string Segment { get; set; }
        public int Time { get; set; }
        public double Speed { get; set; }
    }
}

The populated list has about 70 list items. I've had problems feeding the List as a source to the Chart. I'd like the Time values to be the marks on the X axis, and Speed values to be the points on the said X mark. The picture illustrates:

enter image description here

I've tried the solution posted Here, no errors but my chart shows up just an empty area. The code in the Form1 is:

        chart1 = new Chart();

        chart1.DataSource = list;

        chart1.Series.Add("Speed").YValueMembers = "Speed";
        chart1.Series["Speed"].ChartType = SeriesChartType.Bar;
        chart1.Series["Speed"].XValueType = ChartValueType.Double;
        chart1.Series["Speed"].YValueType = ChartValueType.Double;

Any Advice how to bind the List as the datasource for the chart? The forums are rather scarce on said topic.

Upvotes: 2

Views: 1302

Answers (1)

jsanalytics
jsanalytics

Reputation: 13188

Try this:

    private void Form1_Load(object sender, EventArgs e)
    {
        list = new List<Entry>
        {
            new Entry {Time = 1, Speed = 80, Segment = "Seg 1" },
            new Entry {Time = 2, Speed = 40, Segment = "Seg 2" },
            new Entry {Time = 3, Speed = 100, Segment = "Seg 3" },
            new Entry {Time = 4, Speed = 20, Segment = "Seg 4" },
            new Entry {Time = 5, Speed = 60, Segment = "Seg 5" },
        };

        chart1 = new Chart();
        chart1.Dock = DockStyle.Fill;
        chart1.ChartAreas.Add("ChartArea1");

        chart1.Series.Add("Speed");
        chart1.Series["Speed"].ChartType = SeriesChartType.Column;
        chart1.Series["Speed"].XValueMember = "Time";
        chart1.Series["Speed"].YValueMembers = "Speed";

        chart1.DataSource = list;
        chart1.DataBind();

        Controls.Add(chart1);
    }

enter image description here

EDIT: Adding a button Click event:

    private void Form1_Load(object sender, EventArgs e)
    {
        chart1 = new Chart();
        chart1.Dock = DockStyle.Fill;
        chart1.ChartAreas.Add("ChartArea1");

        chart1.Series.Add("Speed");
        chart1.Series["Speed"].ChartType = SeriesChartType.Column;
        chart1.Series["Speed"].XValueMember = "Time";
        chart1.Series["Speed"].YValueMembers = "Speed";

        list = new List<Entry>();

        chart1.DataSource = list;

        panel1.Controls.Add(chart1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        list.Add(new Entry { Time = i, Speed = i * 10, Segment = i.ToString() });
        chart1.DataBind();

        i++;
    }

Upvotes: 1

Related Questions