This is the code which I use to create 100 stack panels, each with 2 labels in it:
for (int i = 0; i < 100; i++)
{
Border border = new Border();
StackPanel panel = new StackPanel();
panel.Children.Add(new Label { Content = i, Name = ("RAM" + i), Height = 25, VerticalAlignment = VerticalAlignment.Top}); //Label to display RAM Address
panel.Children.Add(new Separator { });
panel.Children.Add(new Label { Content = "000", Name = ("OpCode" + i), Height = 25, VerticalAlignment = VerticalAlignment.Bottom}); //Label to display Operator code
RamArray.Children.Add(panel); //Adding StackPanel
}
And the code below is what I use to find the "OpCode" label:
for (int i = 0; i < InputBox.LineCount; i++)
{
var opcodelabel = RamArray.FindName("OpCode" + i) as Label;
RAM[i] = InputBox.GetLineText(i);
opcodelabel.Content = RAM[i];
}
The issue I am having is that I get this error when running the code and it points me to the opcodelabel.Content = RAM[i]; line:
An unhandled exception of type 'System.NullReferenceException' occurred in LittleManComputer Project.exe. Additional information: Object reference not set to an instance of an object.
I have tested this method with a stack panel and label I made in the designer and the code works in that case, however as soon as I try to use it on something I created in my code then it doesn't work anymore.
Edit: Question is not a duplicate, suggested duplicate doesn't explain anything to do with FindName()