2013-04-16 158 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); 
相关问题