Search code examples
c#sql.netchartsmschart

How To Bind A DataTable To MS Chart


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.


Solution

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

    enter image description here

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