0

I am trying to pull records from sql server by using SqlDataReader and dump to a List. I am having object reference not set to instance of an object error. Below is the code.

        private List<Models.AreasOfLaw> aolTitles;

    public List<Models.AreasOfLaw> AreasOfLawListItems
    {
        get { return aolTitles; }
        set { aolTitles = value; OnPropertyChanged("AoLTitles"); }
    }

    private void GetAllAreasOfLaws()
    {
        try
        {
            using (SqlConnection sqlConnection = new SqlConnection(DataSources.RemoteConnectionString()))
            {
                sqlConnection.Open();
                string commandText = "SELECT AreaOfLawTitle FROM [dbo].[CLR.AreaOfLaw] ORDER BY AreaOfLawTitle";
                using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
                {
                    sqlCommand.CommandType = CommandType.Text;
                    SqlDataReader reader = sqlCommand.ExecuteReader();
                    while (reader.Read())
                    {
                        string aolTitle = Convert.ToString(reader["AreaOfLawTitle"]);


                        AreasOfLawListItems.Add(new Models.AreasOfLaw { AreaOfLawTitle = aolTitle });
                    }
                    int n = AreasOfLawListItems.Count;
                }
                sqlConnection.Close();

            }
        }
        catch (Exception ex)
        {

        }
    }

I am desperate folks. Thank you.

Bainn
  • 29
  • 8

1 Answers1

1

Your list aolTItles is never initiliased.

Your code should look like this

private List<Models.AreasOfLaw> aolTitles = new List<Models.AreasOfLaw>();

public List<Models.AreasOfLaw> AreasOfLawListItems
{
    get { return aolTitles; }
    set { aolTitles = value; OnPropertyChanged("AoLTitles"); }
}

Declaring a variable and intiliasing it are 2 separate steps, and you can't use a variable until you've initialised it.

WhatsThePoint
  • 3,267
  • 8
  • 27
  • 47
Dave
  • 2,216
  • 2
  • 13
  • 38