0

I have one problem for calling user control from another user control my code like this :

 public UserControl1()
        {
            InitializeComponent();
}

        private void commandBarButtonInsert_Click(object sender, EventArgs e)
        {


            UserControl2 usr2 = new UserControl2();
            this.Hide();
            this.Parent.Controls.Add(usr2);
}

it is returning this error :

System.NullReferenceException: Object reference not set to an instance of an object

. How can I solve this problem ?

Rai Vu
  • 1,595
  • 1
  • 20
  • 30
Sezer Erdogan
  • 167
  • 1
  • 9
  • 34

3 Answers3

1

The problem is that you are not trying to add a control to the parent (maybe Form1) but you are trying to add the UserControl2 as parent of UserControl1. That is not possible.

Quick and dirty would be something like this:

        UserControl2 usr2 = new UserControl2 ();
        this.Hide();
        Form1 parentForm = (this.Parent as Form1);

        parentForm.Controls.Add(new usr2());
M Stoerzel
  • 300
  • 1
  • 13
0

Try referencing controls with x:Name, and access them with the specified name if they are in the same XAML file.
Edit: Also, if you're getting a NullReferenceException, the problem lies within you calling a method on a NULL object.

TheITDejan
  • 808
  • 9
  • 27
0

this.Parent is null, a basic form has no parent, but panel, for example, may have `Parent property.

Also, if you wanted to do something like this.Controls.Add(usr2); you will get System.ArgumentException because of you cant add form to another form (without any containers)

styx
  • 1,852
  • 1
  • 11
  • 22