如何使用c#绘制图表

本文关键字:绘制 何使用 | 更新日期: 2023-09-27 17:58:15

我必须使用c#绘制条形图。首先,我尝试使用vb.net使用System.Windows.Forms.DataVisualization.Charting名称空间。下面的代码

    Dim strConn As  string MyConString = "SERVER=localhost;" + "DATABASE=demo;" + "UID=root;" + "PASSWORD=root;";
    Dim conn As New SqlConnection(strConn)
    Dim sqlProducts As String = "SELECT Top 8 ProductName, UnitsInStock FROM Products"
    Dim da As New MYSqlDataAdapter(sqlProducts, conn)
    Dim ds As New DataSet()
    da.Fill(ds, "Products")
    Dim ChartArea1 As ChartArea = New ChartArea()
    Dim Legend1 As Legend = New Legend()
    Dim Series1 As Series = New Series()
    Dim Chart1 = New Chart()
    Me.Controls.Add(Chart1)
    ChartArea1.Name = "ChartArea1"
    Chart1.ChartAreas.Add(ChartArea1)
    Legend1.Name = "Legend1"
    Chart1.Legends.Add(Legend1)
    Chart1.Location = New System.Drawing.Point(13, 13)
    Chart1.Name = "Chart1"
    Series1.ChartArea = "ChartArea1"
    Series1.Legend = "Legend1"
    Series1.Name = "Series1"
    Chart1.Series.Add(Series1)
    Chart1.Size = New System.Drawing.Size(800, 400)
    Chart1.TabIndex = 0
    Chart1.Text = "Chart1"
    Chart1.Series("Series1").XValueMember = "date"
    Chart1.Series("Series1").YValueMembers = "temperature"
    Chart1.DataSource = ds.Tables("flowchart")

它的工作原理与我尝试使用c#完全相同

        string MyConString = "SERVER=localhost;" + "DATABASE=demo;" + "UID=root;" + "PASSWORD=root;";
        MySqlConnection con = new MySqlConnection(MyConString);
        con.Open();
        string s = "select date,temperature from flowchart";
        MySqlDataAdapter da = new MySqlDataAdapter(s, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "flowchart");
        ChartArea chartarea1 = new ChartArea();
        Legend legend = new Legend();
        Chart c1 = new Chart();
        Series series = new Series();
        Controls.Add(c1);
        chartarea1.Name = "ChartArea";
        c1.ChartAreas.Add(chartarea1);
        legend.Name = "Legend";
        c1.Legends.Add(legend);
        c1.Location = new System.Drawing.Point(13, 13);
        series.Name = "Series";
        c1.Series.Add(series);
        c1.Size = new System.Drawing.Size(800, 400);
        c1.TabIndex = 0;
        c1.Text = "Chart1";
        c1.Series("Series").XValueMember = "date";
        c1.Series("Series").YValueMembers = "temperature";
        c1.DataSource = ds.Tables("flowchart");

最后三行出错。我不知道这是不是正确的方法。

如何使用c#绘制图表

在C#中,当您在列表/集合或数组中提供参数时,它应该写在方括号[]中。只有方法或函数的参数可以具有圆括号()

它应该像这个一样写

c1.Series["Series"].XValueMember = "date";`

看起来Chart.Series是一个属性,它返回SeriesCollection

如果要将Series.XValueMemberSeries.YValueMembers属性用于它,则需要将索引器(ChartNamedElementCollection<T>.Item Property (String))与它一起使用,如;

c1.Series["Series"].XValueMember = "date";
c1.Series["Series"].YValueMembers = "temperature";