2013-04-16 261 views
0

我有一個MainForm在哪裏打開另一個窗體,現在我有一個類,它提供了一些函數,我寫了一個函數獲取主窗體的引用和打開窗體的引用和其他參數我打開窗體中的函數調用,並引用MainForm我使用this.Parent,但我得到錯誤「對象引用沒有設置在一個opject的實例」。引用父窗體從子窗體

*客戶方是我的MainForm *登錄名是我在MainForm的打開和形式,其中我調用該方法RunListener

class ServicesProvider 
{ 
public static void RunListener(ClientSide MainForm,LogIn LogForm,System.Net.Sockets.TcpClient Client) 
    { 
    //Doing my things with the parameters 
    } 
} 

這個代碼是在登錄表單

private void BtLogIn_Click(object sender, EventArgs e) 
    { 
    Thread Listener = new Thread(delegate() 
       { 
        ServicesProvider.RunListener((ClientSide)this.Parent,this,tcpClient); 
       }); 
       Listener.Start(); 
    } 

的問題是,每當我調試我得到我告訴你的錯誤,我發現代碼「(ClinetSide)this.parent」引用null。 我需要參考主窗體來處理它並更改一些值。

+0

你顯示子窗體像這樣:? 'child.Show(parent);'或'child.ShowDialog(parent);' –

+0

LogIn LogForm = new LogIn(); LogForm.ShowDialog(); 這樣的 –

+0

thax @PeterRitchie你啓發了我,我改變了LogIn窗體構造函數,讓它得到一個ClientSide參數。 LogIn LogForm = new LogIn(this); LogForm.showDialog(); –

回答

0

假設在Form1 =父

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace childform 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Form2 tempDialog = new Form2(this); 
      tempDialog.ShowDialog(); 
     } 

     public void msgme() 
     { 
      MessageBox.Show("Parent Function Called"); 
     } 

    } 
} 

1和Form 2 =兒童

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace childform 
{ 
    public partial class Form2 : Form 
    { 
     private Form1 m_parent; 

     public Form2(Form1 frm1) 
     { 
      InitializeComponent(); 
      m_parent = frm1; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      m_parent.msgme(); 
     } 
    } 
} 
+0

輝煌的答案非常感謝 –

+0

歡迎您和weclome堆棧溢出! –

2

表單默認情況下不知道「父」,您必須告訴它。例如:

LogForm.ShowDialog(parentForm); 
相關問題