-2

I have a C# WPF application with a form in it. The form is supposed to take two values(firstName and lastName) and then use the Instructor class to add it to my listview element. On the line instList.Add(new Instructor... I am getting the error object reference not set to instance of an object. Why does this happen?

This is my mainwindow.xaml.cs:

namespace AssignmentTwoPartTwo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public List<Instructor> instList;
        public MainWindow()
        {
            InitializeComponent();
            List<Instructor> instList = new List<Instructor> { };
            lvInstructorList.ItemsSource = instList;
        }

        private void btnCreateInstructor_Click(object sender, RoutedEventArgs e)
        {
            spCreateInstructor.Visibility = (spCreateInstructor.Visibility == Visibility.Hidden) ? Visibility.Visible : Visibility.Hidden;
        }

        private void btnInstructorSubmit_Click(object sender, RoutedEventArgs e)
        {
            instList.Add(new Instructor() { firstName = txtInstructorFirstName.Text, lastName = txtInstructorLastName.Text });
            lvInstructorList.ItemsSource = instList;
        }
    }
}

This is Instructor.cs

namespace AssignmentTwoPartTwo
{
    public class Instructor
    {
        public string firstName { set; get; }
        public string lastName { set; get; }
    }
}
ShoeLace1291
  • 4,551
  • 12
  • 45
  • 81

2 Answers2

0

Pays to use a debugger here, you have 3 things that could cause it

instList.Add
txtInstructorFirstName.Text
txtInstructorLastName.Text

I'd say the top one is least likely.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

You are redeclaring the instList in the constructor, which shadows your instance variable. If you change your constructor to this, it should work:

public MainWindow()
{
    InitializeComponent();
    instList = new List<Instructor> { };
    lvInstructorList.ItemsSource = instList;
}
Nico
  • 3,542
  • 24
  • 29