【问题标题】:How to pass value from user control to its parent form?如何将值从用户控件传递到其父窗体?
【发布时间】:2014-12-03 17:53:19
【问题描述】:

我有一个用户控件,据说它会将值传递给它的父表单,即 form1。

我使用了下面的代码。

用户控制

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

Form1 为 UserControl 赋值

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

用户控制按钮_点击

 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;

它返回一个空引用异常。

请帮忙!!!

【问题讨论】:

标签: c# user-controls


【解决方案1】:

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

事实上,这个演员阵容:

this.Parent as Form1

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多