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 {}
}
}