.net chart clear and re-add

I Faced kind of problem(but for windows form Application). So can you please tell me when are you passing the datasource to the charts.

I Used incorrect order while passing the data to the chart control

At first time I did this :

chart1.Series["Series1"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Auto;

chart1.DataSource = sqlChartTabel; //sqlChartTable is my DataTable
// Assigning new Data to the charts
chart1.Series.Clear();   // clearing chart series (after the DataTable is assigned with data)
chart1.Series.Add("Violations");
chart1.Series["Series1"].XValueMember = "Month_name";
chart1.Series["Series1"].YValueMembers = "Salary";
chart1.ChartAreas["ChartArea1"].AxisX.Title = "Months";
chart1.ChartAreas["ChartArea1"].AxisY.Title = "Salary";
chart1.DataBind();
chart1.Visible = true;

So, then I realized, I am Assigning the data before clearing the chart so I just changed my statement order, And It Worked :

My Working code :

chart1.Series.Clear();   // changed position of clear(before Assigning the datatable)
chart1.Series.Add("Violations");
chart1.Series["Series1"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Auto;
chart1.DataSource = sqlChartTabel;   //sqlChartTable is my DataTable

// Assigning new Data to the charts
chart1.Series["Series1"].XValueMember = "Month_name";
chart1.Series["Series1"].YValueMembers = "Salary";
chart1.ChartAreas["ChartArea1"].AxisX.Title = "Months";
chart1.ChartAreas["ChartArea1"].AxisY.Title = "Salary";
chart1.DataBind();
chart1.Visible = true;

This should work

 chartnameHERE.Series["SeriesNameHERE"].Points.Clear();

This will actually completely remove the series from the chart (not just remove the points from the series).

while (chart1.Series.Count > 0) { chart1.Series.RemoveAt(0); }

This should work:

foreach(var series in chart.Series) {
    series.Points.Clear();
}

Tags:

C#

Asp.Net

Charts