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

}
2
  • Is the collection initialized? In the code you provided I don't see anything along the lines of ToDoListCollection = new List<string>() Commented Jan 27, 2021 at 5:30
  • Does this answer your question? What is a NullReferenceException, and how do I fix it? Commented Apr 3, 2023 at 13:54

1 Answer 1

7

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>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.