Skip to main content

How to: Bind a Chart to an Array List

  • 3 minutes to read

This tutorial demonstrates how to bind a chart to data represented in an ArrayList object.

To bind a chart to an array list, do the following:

  1. Start Microsoft Visual Studio, and create a new Windows Forms Application, or open an existing one.
  2. Add a chart to the form.
  3. Declare a class that represents an individual record. The code below declares a class with the ID, Name and Age public properties. These properties will be data source fields.

    public class Record {
        int id, age;
        string name;
        public Record(int id, string name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        public int ID {
            get { return id; }
            set { id = value; }
        }
        public string Name {
            get { return name; }
            set { name = value; }
        }
        public int Age {
            get { return age; }
            set { age = value; }
        }
    }
    
  4. Once the record class has been declared, the data source object can be filled with records. This example will use an ArrayList as the report’s data source. So, there is no need to create a custom object implementing the IList, ITypedList or IBindingList interfaces.

    The code below fills the ArrayList with records and assigns it to the chart’s ChartControl.DataSource property. Then, you can adjust the SeriesBase.ArgumentDataMember and SeriesBase.ValueDataMembers properties of the chart’s series.

    private void Form1_Load(object sender, EventArgs e) {
        // Create a list.
        ArrayList listDataSource = new ArrayList();
    
        // Populate the list with records.
        listDataSource.Add(new Record(1, "Jane", 19));
        listDataSource.Add(new Record(2, "Joe", 30));
        listDataSource.Add(new Record(3, "Bill", 15));
        listDataSource.Add(new Record(4, "Michael", 42));
    
        // Bind the chart to the list.
        ChartControl myChart = chartControl1;
        myChart.DataSource = listDataSource;
    
        // Create a series, and add it to the chart.
        Series series1 = new Series("My Series", ViewType.Bar);
        myChart.Series.Add(series1);
    
        // Adjust the series data members.
        series1.ArgumentDataMember = "name";
        series1.ValueDataMembers.AddRange(new string[] { "age" });
    
        // Access the view-type-specific options of the series.
        ((BarSeriesView)series1.View).ColorEach = true;
        series1.LegendTextPattern = "{A}";
    }
    

Now, the chart has been bound to data. Run the application, and view the result.

HowTo_BindingToLists

See Also