How To Bind A DataTable To MS Chart

2019-09-15 11:38发布

问题:

this is myCode:

 private void frmChart_Load(object sender, EventArgs e)
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        using (SqlConnection Con = new SqlConnection(cs))
        {
            SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable  group by UserName",Con);
            Con.Open();
            SqlDataReader reader = cmdSum.ExecuteReader();
            chart1.DataBindTable(reader,"sum(Value)");
        }
        foreach (Series series in chart1.Series)
        {
            series.CustomProperties = "DrawingStyle=LightToDark";
        }

    }

It shows me an error in chart1.DatabindTable. also I try another method but I could not handle it.

回答1:

If all you're trying to do is to bind a data table, then just do this:

        private void Form1_Load(object sender, EventArgs e)
        {
            string sql = "your sql here";

            SqlDataAdapter adapter = new SqlDataAdapter(sql, connectionString);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            chart1.DataBindTable(dt.DefaultView, "UserName");
        }

Note when calling DataBindTable you have to use "UserName" (xField). Not Value or Sum(Value).



回答2:

check you values into reader.. if you have values,

try replacing

chart1.DataBindTable(reader,"sum(Value)");

with

chart1.DataBindTable(reader,"Value");

once you sum up values into query you need not to mention sum again, your Value parameter will have sum

Edit --- Updated Code..

private void frmChart_Load(object sender, EventArgs e)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            using (SqlConnection Con = new SqlConnection(cs))
            {
                SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable  group by UserName", Con);
                Con.Open();
                SqlDataReader reader = cmdSum.ExecuteReader();
                while (reader.Read())
                {
                    chart1.DataBindTable(reader, reader["Value"]);
                }

            }
            foreach (Series series in chart1.Series)
            {
                series.CustomProperties = "DrawingStyle=LightToDark";
            }

        }