Search code examples
c#windowsformshost

How to send data from one form to another to create a chart


Is it possible to calculate numbers in one form and use it to make a chart in a second form?

I just want to show a line graph which gets the data from a set of numbers being calculated.

I have only been using c# for a week, the only way I know how to make a chart is using numericUpDown on the current form which is not what I want.

like so ...

Point[] pts = new Point[1000];
int count = 0;

pts[count++] = new Point((int)numericUpDown1.Value, (int)numericUpDown2.Value);

for (int i = 0; i < count; i++)
{
    if (i != 0)
    {
        this.CreateGraphics().DrawLine(new Pen(Brushes.Red, 4), pts[i - 1], pts[i]);
    }
    else
    {
        this.CreateGraphics().DrawLine(new Pen(Brushes.Red, 4), pts[i], pts[i]);
    }
}

Solution

  • You can pass data to a new form, and then draw the graph from there. One way would be in the constructor, when you create the new form to draw the graph on, for example:

    Form to calculate graph points (or whatever data you need to draw the graph)

    public class CalculationForm
    {
        public CalculationForm()
        {
            InitializeComponent();
    
            Point[] points = CalculatePoints();
    
            GraphForm graphForm = new GraphForm(points);
            graphForm.Show();
        }
    
        private Point[] CalculatePoints()
        {
            // method to generate points
            return points;
        }
    }
    

    Then in the form you want to draw the graph in:

    public class GraphForm
    {
        public GraphForm(Point[] points)
        {
            InitializeComponent();
            DrawGraph(points);
        }
    
        private void DrawGraph(Point[] points)
        {
            // Code to draw your graph goes here
        }
    }