2014-12-03 116 views
0

我有一個用戶控件,應該將值傳遞給它的父窗體form1。如何將用戶控件的值傳遞給父窗體?

我使用下面的代碼。

用戶控制

public int _control; 
public int control 
{ 
     get{return _control;} 
     set{_control=value;} 
} 

Form1中值分配給用戶控件

UserControl1 uc=new UserControl1(); 
uc.control=1; 

用戶控制Button_Click

var parent = this.Parent as Form1; 
//MessageBox.Show(_control.ToString()); 
parent.userNo=_control; 

Form1中

public int _userNo; 
public int userNo 
{ 
     get{return _userNo;} 
     set{_userNo=value;} 
} 

問題是,當我用messagebox.show,它會出現顯示1但是當我使用

parent.userNo=_control; 

它返回一個空引用異常。

請幫忙!!!

+0

的可能重複[?什麼是一個NullReferenceException,我如何修復它(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how- do-i-fix-it) – Sinatr 2014-12-03 09:48:33

回答

0

這意味着父母是空的。這是由於父母不是Form1類的實例。

其實,這個轉換:

this.Parent as Form1 

返回NULL時this.Parent不是類型Form1的,但另一個容器。或者,如果家長沒有設置。要解決這個問題,您需要獲取Form的引用給用戶控件,或者設置父級。是這樣的:

UserControl1 uc=new UserControl1(); 
uc.control=1; 
uc.Parent = this; 
+0

謝謝!我爲此使用了委託。 – 2015-01-17 19:45:21

相關問題