简体   繁体   中英

from datagridview to chart C# doubling the first row

I have a script that at some point creates a chart from a DataGrid, this DataGrid contains 3 columns: now the problem is that when the chart is generated the first row is always getting doubled and puts it in between all the other bars in the chart.

Example - Let's say if the chart should be ABC however, instead of AAB -AC like wise.

Refer to screenshot here - resulting chart

The source code I used is this:

 for (int i = 0; i < dataGridView1.Rows.Count; i++) 
 {
  this.chart1.Series["Spent hr"].Points.AddXY(dataGridView1.Rows[i].Cells[0].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value.ToString()));
  this.chart1.Series["Budgeted hr"].Points.AddXY(dataGridView1.Rows[i].Cells[0].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()));
 }

ok i have no idea why this works but adding this code just after the initialisation of the for cycle resolved the issue, it was not only the first row bein duplicated but every rows after it was put in:

                        if (i == dataGridView1.Rows.Count - dataGridView1.Rows.Count)
                        {
                            foreach (var series in chart1.Series)
                            {
                                series.Points.Clear();
                            }

                        }

Try this out -

    //filling the Coloumns
    dataGridView1.Rows.Clear();
    dataGridView1.Columns.Clear();

    dataGridView1.Columns.Add("name", "Column1");
    dataGridView1.Columns.Add("budgetedhr", "Column2");
    dataGridView1.Columns.Add("spenthr", "Column3");

    // filling in Rows with some data
    dataGridView1.Rows.Add("Jhon", 21, 23);
    dataGridView1.Rows.Add("Nicol", 31, 2);
    dataGridView1.Rows.Add("Matteo", 23, 41);

    // Now we can set up the Chart:
    List<Color> colors = new List<Color> { Color.Green, Color.Red};

    chart1.Series.Clear();

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        Series S = chart1.Series.Add(dataGridView1[0, i].Value.ToString());
        S.ChartType = SeriesChartType.Column;
        S.Color = colors[i];
    }

    // and fill in all the values from the dgv to the chart:
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        for (int j = 1; j < dataGridView1.Columns.Count; j++)
        {
            int p = chart1.Series[i].Points.AddXY(dataGridView1.Columns[j].HeaderText, dataGridView1[j, i].Value);
        }
    }

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