如何将值从用户控件传递到其父窗体?

时间:2014-12-03 09:38:54

标签: c# user-controls

我有一个用户控件,可以将值传递给它的父窗体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;

Form1中

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

问题是当我使用messagebox.show时,它会显示1但是当我使用

 parent.userNo=_control;

它返回Null Reference Exception。

请帮助!!!

1 个答案:

答案 0 :(得分:0)

这意味着父母是空的。这是因为父级不是Form1类的实例。

事实上,这个演员:

this.Parent as Form1
当this.Parent不是Form1类型时,

返回NULL,但是是另一个容器。或者,如果未设置父级。要解决此问题,您需要将表单的引用添加到用户控件,或者设置父级。类似的东西:

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