Home > Blockchain >  Reaching chart from another form
Reaching chart from another form

Time:11-22

I have a chart on form1 and I am trying to reach that chart form form2. For example getting the name of the series. It gives me this 'Object reference not set to an instance of an object.' Chart's modifier is Public (I try also internal). I don't understand why. Any ideas

TrackerV2 tv2 = ActiveForm as TrackerV2; //reaching main form with this
MessageBox.Show(tv2.chartMonthlyReport.Series[0].Name.ToString());

CodePudding user response:

Here is a minimal example of how to use an event to signal back to form1.

void Main()
{
    var form1 = new Form1();
    form1.Show();
}

public class Form1 : Form
{
    private Button Button1;
    private Chart chartMonthlyReport;

    public Form1()
    {
        this.Button1 = new Button() { Text = "Open Form 2", Width = 256, };
        this.Button1.Click  = (s, e) =>
        {
            var form2 = new Form2();
            form2.DisplaySeriesName  = (s2, e2) =>
                MessageBox.Show(chartMonthlyReport.Series[0].Name);
            form2.ShowDialog();
        };
        this.chartMonthlyReport = new Chart();
        this.chartMonthlyReport.Series.Add(new Series() { Name = "Monthly" });
        this.Controls.Add(this.Button1);
    }
}

public class Form2 : Form
{
    private Button Button1;
    public event EventHandler DisplaySeriesName;

    public Form2()
    {
        this.Button1 = new Button() { Text = "Display Series Name", Width = 256, };
        this.Button1.Click  = (s, e) =>
            this.DisplaySeriesName?.Invoke(this, new EventArgs());
        this.Controls.Add(this.Button1);
    }
}

When I run this I get this:

enter image description here

  • Related