0
@for (int i = 0; i < values.Count; i++)
{
    <input type="checkbox" @bind="values[i]" />
}
@code {
    private List<bool> values = new List<bool>() { true, true, false };
}

Why did the following exception occur when I clicked the "checkbox" generated by the above code?

Unhandled exception rendering component: Index was out of range. Must be non-negative and less than the size of the collection.

What is the right way? Thanks a lot.

2 Answers2

2

In your for loop you iterate over i. In each iteration, the value of i is increased by one. The value is not bound to let's say values[1] but to values[i] which is after the last iteration 3 for each element. 3 violates the array boundaries, hence the exception.

The underlying reason is that a lambda expression is used to make this binding. In this lambda expression i is not a value, but a reference. Have a look at this post for a similar example.

To prevent it, add a new variable inside the for loop to save the current value of i.

@for (int i = 0; i < values.Count; i++)
{
    var temp = i;
    <input type="checkbox" @bind="values[temp]" />
}

Just the benno
  • 2,306
  • 8
  • 12
0

This is a result of C# behaviour. You can use a foreach loop or capture the variable.

@for (int i = 0; i < values.Count; i++)
{
    var iCopy = i;
    <input type="checkbox" @bind="values[iCopy]" />
}
Brian Parker
  • 11,946
  • 2
  • 31
  • 41