winforms 从数据网格视图到图表C#第一行加倍

lxkprmvk  于 2022-12-23  发布在  C#
关注(0)|答案(2)|浏览(148)

我有一个脚本,在某个时候从一个数据网格创建一个图表,这个数据网格包含3列:现在的问题是,当生成图表时,第一行总是加倍,并将其置于图表中的所有其他条之间。
例如-让我们说,如果图表应该是A-B-C然而,而不是A-A-B -A-C一样明智。
参见此处的屏幕截图-resulting chart
我使用的源代码是:

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()));
 }
owfi6suc

owfi6suc1#

好吧,我不知道为什么会这样,但是在for循环初始化后添加这段代码解决了这个问题,不仅第一行被复制,而且每一行都被复制:

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

                        }
axkjgtzd

axkjgtzd2#

试试这个-

// filling the columns
    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);
        }
    }

相关问题