【问题标题】:C# charting - two chart areas with different Y valuesC# 图表 - 具有不同 Y 值的两个图表区域
【发布时间】:2017-08-09 23:24:37
【问题描述】:

编程的好日子,

我有一个问题。我编写了一个代码来创建带有 datagridview 的图表作为chartarea1 的数据源。

Chart chart1 = new Chart();
        chart1.Size = new System.Drawing.Size(1024, 768);


        ChartArea chartArea1 = new ChartArea();
        chartArea1.AxisX.MajorGrid.LineColor = Color.LightGray;
        chartArea1.AxisY.MajorGrid.LineColor = Color.LightGray;
        chartArea1.AxisX.LabelStyle.Font = new Font("Consolas", 8);
        chartArea1.AxisY.LabelStyle.Font = new Font("Consolas", 8);
        chartArea1.AxisX.IntervalType = DateTimeIntervalType.Months;
        chartArea1.AxisX.Interval = 1;
        chart1.ChartAreas.Add(chartArea1);



        chart1.Series.Add(new Series());

        chart1.Series[0].XValueMember = dataGridView1.Columns[0].DataPropertyName;
        chart1.Series[0].YValueMembers = dataGridView1.Columns[1].DataPropertyName;
        chart1.DataSource = dataGridView1.DataSource;

        chart1.Series[0].ChartType = SeriesChartType.Line;

现在我想在chart1 中创建第二个chartarea,它具有相同的XValueMember 但来自不同datagridview 的不同YValueMember,例如datagridview2。有可能吗?

提前致谢。


好的,所以我尝试了这个:

            Chart chart1 = new Chart();
        ChartArea chartArea1 = new ChartArea();
        Series series1 = new Series();
        chart1.DataSource = dataGridView1.DataSource;

        chartArea1 = chart1.ChartAreas.Add("ca1");
        chartArea1.AxisX.MajorGrid.LineColor = Color.LightGray;
        chartArea1.AxisY.MajorGrid.LineColor = Color.LightGray;
        chartArea1.AxisX.LabelStyle.Font = new Font("Consolas", 8);
        chartArea1.AxisY.LabelStyle.Font = new Font("Consolas", 8);
        chartArea1.AxisX.IntervalType = DateTimeIntervalType.Months;
        chartArea1.AxisX.Interval = 1;

        series1 = chart1.Series.Add("s1");

        series1.Points.DataBindXY(dataGridView1.Columns[0].DataPropertyName, dataGridView1.Columns[1].DataPropertyName);

        series1.ChartType = SeriesChartType.Line;

        chart1.SaveImage("chart.png", ChartImageFormat.Png);

现在出现这个错误:

Y 值不能是绑定到字符串对象的数据。 参数名称:yValues

【问题讨论】:

    标签: c# charts datagridview


    【解决方案1】:

    你不应该绑定到整个Chart,而是绑定到Series.Points

    Chart DataBinding有多种使用方式

    您还应该控制每个SeriesChartAreasName;当您想要/需要将第二个系列与第二个图表区关联时,这一点很重要。

    添加ChartAreaSeries 的首选/推荐方式如下:

    chartArea1 = chart1.ChartAreas.Add("ca1"); // or any other, more useful name
    
    Series series1 = chart1.Series.Add("s1");  // dito
    

    关联是这样完成的:

    series1.ChartArea  = "ca1";   // note the string!!
    

    只绑定一个系列使用..

    series1.Points.DataBindXY()  
    

    ..或顶部链接中的表格中的其他一些重载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      相关资源
      最近更新 更多