5

I'm a beginner at Blazor and am making a simple to-do list project. I got an error when adding a list. Unhandled exception rendering component: Object reference not set to an instance of an object.

System.NullReferenceException: Object reference not set to an instance of an object. at FrontEnd.Pages.Index.AddList(KeyboardEventArgs e) in C:\Users\bryan\source\repos\Productivity_App\FrontEnd\Pages\Index.razor.cs:line 20 at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

I tried searching for the problem and found a similar post but the answer didn't help me at all, looking at the question. I think it has something to do with blazor lifecycle to fix it. Here's the code related to the error.

Index.razor:

<div class="toDoList">
    @if (ToDoListCollection != null)
    {
        @foreach (string toDoList in ToDoListCollection)
        {
            <input type="checkbox" id="checkbox">
            <label for="checkbox">@toDoList</label>
            <hr />
        }
    }
    else {}
</div>

Index.razor.cs

public partial class Index
{
    public bool IsCompleted { get; set; }
    public string Description { get; set; }
    public List<string> ToDoListCollection { get; set; }
    
    public void AddList(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(Description) || e.Key == "NumpadEnter" && !string.IsNullOrWhiteSpace(Description))
        {
            ToDoListCollection.Add($"{Description}"); // This is the line that the error message is referencing 
            Description = null;
        } 
        else {}
    }

}
spaleet
  • 838
  • 2
  • 10
  • 23
TheNoobProgrammer
  • 1,013
  • 4
  • 10
  • 21
  • Is the collection initialized? In the code you provided I don't see anything along the lines of `ToDoListCollection = new List()` – Nijenhof Jan 27 '21 at 05:30
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Timothy G. Apr 03 '23 at 13:54

1 Answers1

6

I assume that your ToDoListCollection has null value because it is not inialized.

Assign a default value to your collection.

public List<string> ToDoListCollection { get; set; } = new List<string>();
puko
  • 2,819
  • 4
  • 18
  • 27