Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
A little Background.. I am trying to access the MainWindow's Grid of which my UserControls are being shown.. So i've been able to add and switch between UserControls in my application. HOWEVER after further development i realised an error:

C#
private void ChangeToSecondUserControl()
          {
            SecondUserControl sC = new SecondUserControl();
            var _Main = new MainWindow();
            var Grid = _Main.grdContent;
            int Count = ((Grid)Parent).Children.Count;
            if(Count == 1)
            {
                //int gridIndex = ((Grid)Parent).Children.IndexOf(this);
                //((Grid)Parent).Children.RemoveAt(gridIndex);
                ((Grid)Parent).Children.Add(sC);
            }
        }  


This is the method in which i'm using to traverse between my UserControls. What i discovered was that as i was experimenting, i hadn't been removing the initial UserControl (meaning the second one would load.. however the initial would be directly underneath it)

When i uncomment the commented code, it gives me a NullReference error when it comes to ((Grid)Parent.Children.Add(sC); Could someone explain to me why this is happening?

Note: Even if i have the single line
C#
((Grid)Parent).Children.Remove(0);
(meaning the first child) it gives me an error on that line.. Even if i use
C#
((Grid)Parent).Children.Clear();
Again, when it gets to
C#
((Grid)Parent.Children.Add(sC);
It causes the NullReference Exception again.
Posted
Comments
Richard Deeming 27-May-15 15:14pm    
You'll need to debug your code, but my guess would be that Parent is null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900