0
votes

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 the problem and found a similar post here 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

namespace FrontEnd.Pages
{
    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
            {}
        }
1
Is the collection initialized? In the code you provided I don't see anything along the lines of ToDoListCollection = new List<string>() - Nijenhof

1 Answers

1
votes

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