[英]How to pass value from user control to its parent form?
我有一個用戶控件,該控件將值傳遞給其父窗體form1。
我用下面的代碼。
用戶控制
public int _control;
public int control
{
get{return _control;}
set{_control=value;}
}
Form1將值分配給UserControl
UserControl1 uc=new UserControl1();
uc.control=1;
用戶控件Button_Click
var parent = this.Parent as Form1;
//MessageBox.Show(_control.ToString());
parent.userNo=_control;
表格1
public int _userNo;
public int userNo
{
get{return _userNo;}
set{_userNo=value;}
}
問題是當我使用messagebox.show時,它將顯示為1,但是當我使用
parent.userNo=_control;
它返回一個空引用異常。
請幫忙!!!
這意味着父級為Null。 這是因為父級不是類Form1的實例。
實際上,此強制轉換:
this.Parent as Form1
當this.Parent不是Form1類型,而是另一個容器時,返回NULL。 或者,如果未設置父級。 要解決此問題,您需要獲取用戶控件對Form的引用,或者設置父控件。 就像是:
UserControl1 uc=new UserControl1();
uc.control=1;
uc.Parent = this;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.