如何使用c#绘制图表?

时间:2014-04-14 06:46:10

标签: c# database vb.net winforms charts

我必须使用c#绘制条形图。首先,我尝试使用System.Windows.Forms.DataVisualization.Charting namespace.code下面的

来使用vb.net
    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");

在最后三行收到错误。我不知道这是不正确的方法。

2 个答案:

答案 0 :(得分:1)

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

如果您想使用Series.XValueMemberSeries.YValueMembers属性,则需要使用索引器(ChartNamedElementCollection<T>.Item Property (String));

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

答案 1 :(得分:1)

在C#中,当您在list / collection或array中提供参数时,它应该用方括号[]编写。只有方法或函数的参数可以有圆括号()。 `

应该像这样写

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