winforms 从另一个窗体访问图表

v7pvogib  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(128)

我在form1上有一个图表,我试图访问该图表表单form2。例如,获取序列的名称。它给我这个“对象引用未设置为对象的示例”。Chart的修饰符是Public(我也尝试internal)。我不明白为什么。有什么想法吗

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

7eumitmz1#

以下是如何使用事件向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);
    }
}

当我运行这个程序时,我得到了这个:

相关问题