Home > Software engineering >  Dynamically add ChartAreas to Chart in a column and make Chart auto-scrollable in winforms
Dynamically add ChartAreas to Chart in a column and make Chart auto-scrollable in winforms

Time:12-04

I need your advice. I want to add many ChartAreas to my Chart and align them vertically in one column which would be 100% width of its parent and which would become scrollable when more chat areas are added. For now, I use this code to add more chart areas:

private void AddChartArea(int index)
{
    string chartAreaName = index.ToString();
    chart.ChartAreas.Add(chartAreaName);
    chart.Series.Add(new Series());
    chart.Series[index].ChartType = SeriesChartType.Line;
    chart.Series[index].MarkerStyle = MarkerStyle.Diamond;
    chart.Series[index].ChartArea = chartAreaName;

    /* Trying to align chart areas vertically */
    chart.ChartAreas[index].AlignWithChartArea = chart.ChartAreas[index - 1].Name;
    chart.ChartAreas[index].AlignmentStyle = AreaAlignmentStyles.AxesView;
    chart.ChartAreas[index].AlignmentOrientation = AreaAlignmentOrientations.Vertical;
}

But my chart areas are still going this way when chart areas number is > 3: enter image description here

While I want it to be like this but with a vertical scrollbar on the right: enter image description here

CodePudding user response:

So, as TaW has pointed out, my question is similar to this one. But I've made some improvements to automatically adjust overall Chart height.

So my Chart is placed into Panel, which has AutoScroll true. Then, every time I create a new ChartArea a call this method:

private void DrawNewChartArea(int index)
{
    int chartAreaMinHeight = 200;
    chart.Dock = DockStyle.Top;

    float width = 99;
    float height = 100 / chart.ChartAreas.Count;
    float x = 0;
    float y = height * index;

    if (chartAreaMinHeight * (index   1) > chart.Height)
    {
        chart.Height = chartAreaMinHeight * (index   1);
        // realign height of all the chart areas if we are changing chart height
        for (int i = 0; i < chart.ChartAreas.Count; i  )
        {
            float caY = height * i;
            chart.ChartAreas[i].Position.Height = height;
            chart.ChartAreas[i].Position.Y = caY;
        }
    }

    chart.ChartAreas[index].Position = new ElementPosition(x, y, width, height);
}
  • Related