Search code examples
c#chartsreload

c# windows form application clear chart and reload error


I have a c# windows form application.I have 2 charts in my windows form. i also have a combobox and two buttons among others. What i want is according to the text of the combobox, when i press the start button to load different graphs. So at button start event according to value of combobox i call a different function that loads the charts with what i want each time. And the second button , the stop button has the code below in order to clear the charts.

        chart1.Series.Clear();
        chart2.Series.Clear();

Sometimes my code runs ok but there are times that it throws the error " A chart element with the name 'kwh_price' already exists in the 'SeriesCollection'." My code for load the chart is:

        string[] seriesArray = { "kwh_price", "p_cost" };
        for (int i = 0; i < seriesArray.Length; i++)
        {
            this.chart1.Series.Add(seriesArray[i]);
            this.chart1.Series[seriesArray[i]].BorderWidth = 7;
        }

Am i doing something wrong??is there something more needed in order to clear the chart?? And i don't understand why sometimes it runs ok and others not.


Solution

  • Put the clear code in before the load code. That way you can be sure the data is cleared before adding new data.

    chart1.Series.Clear();
    chart2.Series.Clear();
    
    string[] seriesArray = { "kwh_price", "p_cost" };
            for (int i = 0; i < seriesArray.Length; i++)
            {
                this.chart1.Series.Add(seriesArray[i]);
                this.chart1.Series[seriesArray[i]].BorderWidth = 7;
            }