Search code examples
c#winformschartspaneldynamically-generated

C# WinForms How to add Chart to Panel?


I'm trying to add dynamically charts to a panel in C# WinForms but haven't had any success yet.

Situation:
I have a form (Form1) with a button (button1) and a panel. After the button (button1) is clicked a dialog shows up.

When Dialog.Result from the dialog (Form2) is OK, it should add a chart into the panel with some random value. Multiple charts should be able to be added to the panel.

What I tried so far:
I made a separate class (addGraph) where I wrote a function which creates a column chart with 2 values. Than I tried to call the function in the dialog (Form2) class but this didn't worked out like expected and showed nothing in the (Form1) panel.

Question:
How can I achieve to add charts to the Form1 with function calling in Form2?
Also should I use Panel or GraphControl?

Thanks for your help.
Greetings


Solution

  • I guess something like this :

    void Button1_click()
    {
       using (Form2 form2 = new Form2())
       {
          if (form2.DialogResult == DialogResult.OK)
          {
             var chart = create your chart here
             chart.Parent = YourPanel;
          }
       }
    }
    

    if the chart is created on Form2 than it will look more like

    void Button1_click()
    {
       using (Form2 form2 = new Form2())
       {
          if (form2.DialogResult == DialogResult.OK)
          {
             var chart = form2.CreateChart();
             chart.Parent = YourPanel;
          }
       }
    }
    

    and on Form2 you will need a public function called CreateChart() that will create the chart off course