0

This is my method class:

public class MyPublicMethods
    {
        public void userControlAddingMethod(UserControl uc, Panel pnl)
        {
            pnl.Controls.Clear();
            pnl.Controls.Add(uc);
            uc.BringToFront();
            uc.Dock = DockStyle.Fill;
        }
    }

And my main User Control:

public partial class Index0Top : UserControl
    {
        MyPublicMethods My = new MyPublicMethods();
        Form1 form = (Form1)Application.OpenForms["Form1"];
        public Index0Top()
        {
            InitializeComponent();
        }
        //
        Index0Left1 uc1 = new Index0Left1();
        Index0Left2 uc2 = new Index0Left2();
        //
        private void button1_Click(object sender, EventArgs e) //Option1
        {
            My.userControlAddingMethod(uc1, form.pnlLeft);
        }
        private void button2_Click(object sender, EventArgs e) //Option2
        {
            
            My.userControlAddingMethod(uc2, form.pnlLeft);
        }
    }

And this is sub User Control 1:

public partial class Index0Left1 : UserControl

    {
        MyPublicMethods My = new MyPublicMethods();
        Form1 form = (Form1)Application.OpenForms["Form1"];
        public Inde0Left1()
        {
            InitializeComponent();
        }
    }

And this is another sub User Control 2:

public partial class Index0Left2 : UserControl
    {
        MyPublicMethods My = new MyPublicMethods();
        Form1 form = (Form1)Application.OpenForms["Form1"];
        public Index0Left2()
        {
            InitializeComponent();
        }
    }

This is the Form1 contains everything:

public partial class Form1 : Form
    {
        MyPublicMethods My = new MyPublicMethods();
        public Form1()
        {
            InitializeComponent();
        }
        Index0Top uc1 = new Index0Top();
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                My.userControlAddingMethod(uc1, pnlUp);
            }
        }
    }

When I execute the code and call the any UserControl by click_button event I got Null Reference Exception. I don't understand what is the wrong!

Monk
  • 1
  • 2

0 Answers0