How To Bind A DataTable To MS Chart

…衆ロ難τιáo~ 提交于 2019-12-12 04:34:55

问题


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";
            }

        }


来源:https://stackoverflow.com/questions/42298920/how-to-bind-a-datatable-to-ms-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!