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

C# 如何将值从用户控件传递到其父窗体?,c#,user-controls,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; 用户控制按钮\u单击 var parent = thi

我有一个用户控件,它应该将值传递给它的父窗体form1

我使用了下面的代码

用户控制

 public int _control;
 public int control
 {
      get{return _control;}
      set{_control=value;}
 }
Form1将值分配给UserControl

 UserControl1 uc=new UserControl1();
 uc.control=1;
用户控制按钮\u单击

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

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

 parent.userNo=_control;
它返回空引用异常


请帮忙

这意味着父项为空。这是因为父对象不是类Form1的实例

事实上,这组演员:

this.Parent as Form1
当this.Parent不是Form1类型,而是另一个容器时,返回NULL。或者,如果未设置父项。要解决此问题,您需要获取表单对用户控件的引用,或者设置父控件。比如:

UserControl1 uc=new UserControl1();
uc.control=1;
uc.Parent = this;
可能重复的
UserControl1 uc=new UserControl1();
uc.control=1;
uc.Parent = this;