0

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()

Kacper99
  • 5
  • 2
  • How is `RAM[i]` initialized? – wake-0 Nov 15 '16 at 20:11
  • @KevinWallis I initialised RAM[i] earlier and it is available globally. I double checked it is not the issue as I have the value written out in the debug and I have tested the value being written out to a different label and it doesn't crash – Kacper99 Nov 15 '16 at 20:18
  • 1
    Have you checked if `opcodelabel` is `null`? – wake-0 Nov 15 '16 at 20:24
  • Better use an ItemsControl with an appropriate ItemTemplate and a collection of data items in a view model. – Clemens Nov 15 '16 at 20:35

0 Answers0