简体   繁体   中英

c# - Best way to bind multiple lists to multiple chart series

I have several instances of a class containing a BindingList . The list is updated periodically.

public class myclass
{
    public BindingList<double> values;
    public string name;
    //....code

    public void UpdateVaues()
    {
        //Get somevalue
        values.Add(somevalue);
    }
}

Ideally I would like to put several of these lists in something like a DataTable and just do:

chart1.DataSource = datatable;

And then later:

chart1.DataBind();

and have everything updated.

Currently I am just constantly rebinding each list one at a time:

//Inside main form
chart1.Series["one"].Points.DataBindY(myclass1.values);
chart1.Series["two"].Points.DataBindY(myclass2.values);
//...

I can't believe this is the best way. Any ideas?

You could use DataSet with DataTables and an ObservableCollection if you are looking for one source with multiple bindings.

public class myclass
{
    public DataSet dataSet = new DataSet();
    public DataTable dt1;
    public DataTable dt2;

    public ObservableCollection<double> values1;
    public ObservableCollection<double> values2;

    public myclass() {
        values1.CollectionChanged += values1Changed;
    }

    public void CreateTables()
    {
        // Create the DataSet

        // Create the Data Tables
        dt1 = new DataTable();
        dt2 = new DataTable();

        dataSet.Tables.Add(dt1);
        dataSet.Tables.Add(dt1);

        chart1.DataSource = dataSet;
    }

    private void values1Changed(object sender, NotifyCollectionChangedEventArgs args)
    {
        //Get somevalue (what changed)
        dt1.Rows.Add(somevalue);

        chart1.DataBind();
    }
}

Edit: Another possible solution based on BindingSource with multiple BindingList

    public BindingSource bindingSource { get; set; } = new BindingSource();
    public BindingList<BindingList<double>> bindingList { get; set; } = new BindingList<BindingList<double>>();
    public BindingList<double> values1 { get; set; } = new BindingList<double>();
    public BindingList<double> values2 { get; set; } = new BindingList<double>();

    public Form1()
    {
        InitializeComponent();

        bindingList.Add(values1);
        bindingList.Add(values2);

        bindingSource.DataSource = bindingList;

        chart1.DataSource = bindingSource;
    }

Disclaimer: I haven't fully tested this but you can see if it works. You will also need to set the DataMembers on the chart.

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