2014-06-21 17 views
-1

我從另一個類調用方法有問題。 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沒有dipslay「測試」。然而,當我試圖從調用方法相同的方法內部Form1所有元素都執行:

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

當然,這兩個類是公開的。請幫忙。 Regards

+1

您正在創建Form1的新實例。這個實例有它自己的樹視圖和文本框。您正在查看的Form1實例未受您的代碼影響。因爲你沒有調用Obj.Show,所以這個實例不能顯示自己的文本框,你寫了單詞「Test」。相反,當您從第一個Form1實例調用該方法時,一切都按預期工作,因爲該方法適用於第一個實例擁有的樹視圖和文本框 – Steve

+0

這可能是重複的。看看[this](http://stackoverflow.com/q/1157791/3165552) –

+0

在form2 ctor中獲得form1實例,當然你必須在Form1類型的form2中有一個私有字段並在ctor中進行分配,然後在你button2單擊處理程序使用該字段。或僅在您的button2單擊處理程序的地方 - Form1 f =(Form1)Application.OpenForms [「Form1」]; – terrybozzio

回答

1

如果要創建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(); 
} 
+0

謝謝Piotr,我已經更新了代碼。現在它效果很好! :) – user3763057

2

我建議檢索相同的Form1實例,這可能是您實際在屏幕上看到的實例。

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

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

檢索Form1實例有多種方式,如果需要請留言。