0

I have a user control that will supposedly pass value to its parent form which is form1.

I used the code below.

User Control

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

Form1 assign value to UserControl

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

User Control 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;}
 }

The problem is when i used messagebox.show, it will appear displaying 1 but when i used

 parent.userNo=_control;

it returns a Null Reference Exception.

Please help!!!

Jb Mapili
  • 1
  • 2
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Sinatr Dec 03 '14 at 09:48

1 Answers1

0

That means that parent is Null. this is due to the fact that the parent is NOT an instance of the class Form1.

in fact, this cast:

this.Parent as Form1

returns NULL when this.Parent is not of the type Form1, but is another container. alternatively, if the parent is not set. to fix this, you need to get a reference of the Form to the user control or alternatively, set the parent. something like:

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