【问题标题】:Can't call all methods from different Form不能从不同的表单调用所有方法
【发布时间】:2014-06-21 15:05:21
【问题描述】:

我在调用另一个类的方法时遇到问题。 Form1.cs 包含:

public void RefreshTreeview()
{
    MessageBox.Show("test");
    this.treeView1.Nodes.Clear();
    this.textBox10.Text = "test";
}

当我尝试从另一个类“Form2.cs”调用此方法时:

public void button2_Click(object sender, EventArgs e)
{
    Form1 Obj = new Form1();

    Obj.RefreshTreeview();
    this.Close();
}

我只收到带有文本的消息框。 Treeview 没有“清除”,textBox10 没有进行“测试”。但是,当我尝试从 Form1 中的方法调用相同的方法时,所有元素都已执行:

private void toolStripButton1_Click(object sender, EventArgs e)
{
    RefreshTreeview();
}

当然,这两个课程都是公开的。请帮忙。 问候

【问题讨论】:

  • 您正在创建 Form1 的新实例。这个实例有它自己的树视图和文本框。您正在查看的 Form1 实例不受您的代码影响。因为您没有调用 Obj.Show,所以此实例无法在您编写单词“Test”的位置显示其自己的文本框。相反,当您从第一个 Form1 实例调用该方法时,一切都按预期工作,因为该方法适用于第一个实例拥有的树视图和文本框
  • 这可能是重复的。看看this
  • 在 form2 ctor 中获取 form1 实例,当然你必须在 form2 中拥有一个 form1 类型的私有字段并在 ctor 中分​​配它,然后在你的 button2 点击处理程序中使用该字段。或者只是在你的 button2 点击处理程序中地方 - Form1 f = (Form1)Application.OpenForms["Form1"];

标签: c# winforms methods


【解决方案1】:

我建议检索相同的 Form1 实例,这可能是您在屏幕上实际看到的实例。

public void button2_Click(object sender, EventArgs e)
{
    Form1 Obj = // retrieve instead of create a new one

    Obj.RefreshTreeview();
    this.Close();
}

要检索Form1 实例,有多种方法,如果需要,请发表评论。

【讨论】:

    【解决方案2】:

    如果你想创建Form1 的新实例然后清除它,你必须使用Show() 方法。例如:

    public void button2_Click(object sender, EventArgs e)
    { 
        Form1 f = new Form1();
        f.RefreshTreeview();
        f.Show();
    }
    

    但我认为您的目标是清除已经存在的表格。最简单的方法是通知Form2 谁是它的所有者。然后您可以从Form2 访问所有者。 因此,在您用于从Form1 调用Form2 的方法中,而不是使用Show() 方法使用Show(this) - 这样您将当前实例作为新对话框的所有者传递。

    Form1 中的代码,您可以在其中调用 Form2

    Form2 f2 = new Form2();
    f2.Show(this);            // Current window is now the owner of the Form2
    

    现在在Form2 上,您可以访问Form1,删除Nodes 并设置文本:

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Owner == null) return; // Sanity check if there is no owner.
        Form1 f = (Form1)this.Owner;    // Get the current instance of the owner.
        f.RefreshTreeview();            
        f.Show();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多