3

I'd like to use a polar chart in my test application. I've a data table with a couple of columns where the column with the name of "X" should provide the x value members, the others should be the y value members. I found a tutorial on MSDN but it doesn't really work because the line

chart1.DataBindTable(dt, "X");

won't compile. Any tip is welcome and thank you.

Here is the code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace PolarChartTest_01
{
    public partial class Form1 : Form
    {
    public DataTable dt;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dt.Rows.Clear();
        dt.Columns.Clear();
        chart1.Series.Clear();

        dt.Columns.Add("X", typeof(int));
        dt.Columns.Add("Y", typeof(int));

        for (int j = 0; j < 7; j++)
        {
            DataRow dr = dt.NewRow();

            dr["X"] = j * 45;
            dr["Y"] = j;
            dt.Rows.Add(dr);

        }

        chart1.DataBindTable(dt, "X");
    }
}

}

cuongle
  • 74,024
  • 28
  • 151
  • 206
JustGreg
  • 231
  • 2
  • 6
  • 17

3 Answers3

5

It won't compile because DataTable doesn't implement IEnumerable interface. Try:

var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
tukaef
  • 9,074
  • 4
  • 29
  • 45
  • @2kay: AFAIK this was changed with .Net 4.0 - [DataTable](http://msdn.microsoft.com/en-us/library/system.data.datatable%28v=vs.100%29.aspx) inherits from [TypedTableBase](http://msdn.microsoft.com/en-us/library/bb358258%28v=vs.100%29.aspx) which implements IEnumerable and IEnumerable – surfmuggle Jul 15 '14 at 13:01
  • It's funny, because I still can't get it to work directly from a DataTable in .NET 4.0 either, but I agree it looks like it should work by looking at the docs. I get a conversion error from the compiler, that it can't convert from DataTable to IEnumerable. :( – Jonas Jan 21 '16 at 09:51
3

This may help you Write this on page load

chart.DataSource = dataqtableName;
chart.Series["seriesName"].XValueMember = "columNameUwantToBind";
chart.Series["seriesName"].YValueMembers = "columNameUwantToBind";
chart.DataBind();
Community
  • 1
  • 1
Mangal
  • 87
  • 2
  • 11
1

Another solution might be:

chart1.DataBindTable(dt.DefaultView, "X");

As a bonus, the DataView this returns can be used for sorting and filtering, besides being "databindable".

Jonas
  • 1,172
  • 1
  • 16
  • 26