3

I retrieve several datatables from my DB, which vary in size. This one of 2 is just an example.

See the structure here!
enter image description here
I managed to create the 2 different series and have them show up on the legend.

My question is on how to bind that data to the respective series. The series name are created from column doman_namn and the amount of series are created from the "antal" column which holds the number of unique URLS.

QUESTION HOW TO BIND ADDY and ADDX to the chart it fails now.

This is my code so far...

Chart1.DataSource = dt;

int amountofrows = Convert.ToInt32(dt.Rows[0]["antal"].ToString());

for (int i = 0; i < amountofrows; i++)
{
    string serieName = dt.Rows[i]["doman_namn"].ToString();

    Chart1.Series.Add(serieName);
    Chart1.Series[i].ChartType = SeriesChartType.Line;

    foreach(DataRow dr in dt.Rows)
    {
        try
        {
            if (String.Equals(serieName,dr["doman_namn"].ToString(), StringComparison.Ordinal))     
            {
            Chart1.Series[serieName].Points.AddY(Convert.ToDouble(dr["ranking_position"]));
            Chart1.Series[serieName].Points.AddY(Convert.ToDouble(dr["ranking_date"]));
            }
        }
        catch (Exception)
        {
            throw new InvalidOperationException("Failed when adding points");
        }
    }
}


Chart1.DataBind();
Chart1.Visible = true;

CODE AFTER HELP FROM GREGOR

for (int i = 0; i < amountofrows; i++)
{
    string serieName = dt.Rows[i]["doman_namn"].ToString();

    Chart1.Series.Add(serieName);
    Chart1.Series[i].ChartType = SeriesChartType.Line;

    Chart1.Series[serieName].XValueMember = "ranking_date";
    Chart1.Series[serieName].YValueMembers = "ranking_position";

}
Chart1.DataBind();
Necvetanov
  • 374
  • 3
  • 15
8bitcat
  • 2,206
  • 5
  • 30
  • 59

3 Answers3

6

Take a look at one of my samples how to bind DataTable to MS Chart using code:

How to draw Chart based on DataTable from console application?

Hope you will find it usefull.

Here are the key points:

//setting the source from datatable....
chart.DataSource = dt;

//setting XValueMember for first serie (Name is column inside datasource)...
serie1.XValueMember = "ranking_position";

//setting YValueMembers...
serie1.YValueMembers = "ranking_date";

Here is another link for binding multiple series:

http://dotnetslackers.com/articles/net/Binding-a-Microsoft-Chart-with-a-Dataset.aspx

Community
  • 1
  • 1
Gregor Primar
  • 6,759
  • 2
  • 33
  • 46
  • I did take a look but I have everything in my datatable, I just need to know how to add the X and Y points, my data is not double type data. – 8bitcat Nov 12 '12 at 21:21
  • In your case you don't need to add additional points, binding will do the job, just set appropriate XValueMember and YValueMembers. Take a look at my edited answer. – Gregor Primar Nov 12 '12 at 21:35
  • It does not work...I need each doman_namn to be represented by one serie. Now they paint over each other...so one line for alltomkorv.se painted at 3,3,3 and one line for alltomkorv.se/korvfakta painted 100,100,99 – 8bitcat Nov 12 '12 at 21:45
  • Of course, you need to create (add) additional series. XValueMember and YValueMembers are set for specific serie. – Gregor Primar Nov 12 '12 at 21:48
  • This will not work. Row can not be a serie in best case it will be a point. So consider DataTable Rows as one serie. To add additional serie you need to populate new DataTable. – Gregor Primar Nov 12 '12 at 21:54
  • But can't I extract info from the datatable, and add that to points which I then add to the Chart? – 8bitcat Nov 12 '12 at 21:58
  • You can add points manualy by code, but why would you like to do that it you can bind it from DataTable just in 3 lines of code? – Gregor Primar Nov 12 '12 at 22:00
2

I managed to do it myself, but you Gregor Primar pushed me in the right direction!

What was important was that you set the valuetype for the X and Y-axis. As decimal type was not an option I used auto as type.

Chart1.DataSource = dt;

int amountofrows = Convert.ToInt32(dt.Rows[0]["antal"].ToString());

for (int i = 0; i < amountofrows; i++)
{
    List<string> xvals = new List<string>();
    List<decimal> yvals = new List<decimal>();
    string serieName = dt.Rows[i]["doman_namn"].ToString();
    Chart1.Series.Add(serieName);
    Chart1.Series[i].ChartType = SeriesChartType.Line;

    foreach(DataRow dr in dt.Rows)
    {
        try
        {


        if (String.Equals(serieName,dr["doman_namn"].ToString(), StringComparison.Ordinal))     
        {                    
            xvals.Add(dr["ranking_date"].ToString());
            yvals.Add(Convert.ToDecimal(dr["ranking_position"].ToString()));              
        }

        }
        catch (Exception)
        {

            throw new InvalidOperationException("Diagrammet kunde inte ritas upp");
        }
    }
    try
    {
        Chart1.Series[serieName].XValueType = ChartValueType.String;
        Chart1.Series[serieName].YValueType = ChartValueType.Auto;
        Chart1.Series[serieName].Points.DataBindXY(xvals.ToArray(), yvals.ToArray());
    }
    catch (Exception)
    {

        throw new InvalidOperationException("Kunde inte bind punkterna till Diagrammet");
    }    
}

Chart1.DataBind();
Chart1.Visible = true;
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
8bitcat
  • 2,206
  • 5
  • 30
  • 59
0

This might work:

                if (dr.Rows.Count > 0)
                {
                    string[] seriesSessionArray = dr.AsEnumerable().Select(row => row.Field<string>("Username")).ToArray();
                    decimal[] pointsSessionArray = dr.AsEnumerable().Select(row => row.Field<decimal>("Percent")).ToArray();
                    chartGrowth.SuppressExceptions = true;
                    for (int i = 0; i < seriesSessionArray.Length; i++)
                    {
                        if (pointsSessionArray[i] == 0)
                        {
                            chartGrowth.ChartAreas[0].RecalculateAxesScale();
                        }
                        if (chartGrowth.Series.IndexOf(seriesSessionArray[i]) == -1)  //series does not exists
                        {
                            chartGrowth.Series.Add(seriesSessionArray[i]);
                        }
                        chartGrowth.Series[seriesSessionArray[i]].ChartType = SeriesChartType.SplineArea;
                        chartGrowth.Series[seriesSessionArray[i]].Points.AddY(pointsSessionArray[i]);
                        chartGrowth.Series[seriesSessionArray[i]].ToolTip = seriesSessionArray[i] + ":" + "#VAL{0.0}";
                        chartGrowth.Series[seriesSessionArray[i]].SetCustomProperty("LineTension", "0.45");
                    }

                }
Emma
  • 27,428
  • 11
  • 44
  • 69