Binding multiple textboxes to a list

I have a list of items which I am trying to bind to multiple Textboxes, i.e. a Textbox per item. However when I try to change a value in any textbox I get an ArgumentOutOfRangeException. Am I am doing something wrong here?

Test.razor.cs:

public partial class Test
{
    private List<VM> _vms = new List<VM>(4)
    {
        new VM { Type = "1", Value = "1-1" },
        new VM { Type = "2", Value = "2-2" },
        new VM { Type = "3", Value = "3-3" },
        new VM { Type = "4", Value = "4-4" },
    };
}

class VM
{
    public string Type { get; set; } = null!;
    public string Value { get; set; } = null!;
}

Test.razor:

@page "/test"

@for (var i = 0; i < _vms.Count; i++)
{
    <div class="row mt-2 align-items-center">
        <div class="col-md-3">
            <RadzenLabel Text="@_vms[i].Type" />
        </div>
        <div class="col-md-3">
            <div Style="display: inline-flex; width: max-content; align-items: center;">
                <RadzenTextBox Name="SomeName"
                               @bind-Value="_vms[i].Value" Style="width: 100%" Trim="true" />
            </div>
        </div>
    </div>
}

Hi mohamed,

did you solve the problem. I´m facing exactly the issue binding an array to a textbox.

The first loop is working, but it seems when reaching the max value, the IndexOutOfRangeException happens

[edit]
I replaced the Radzen textfield with a normal html input field and it´s working without any problem. So the issue seems to be related to the radzen textbox. Your code is fine.

Hi Fabius,

Thanks for checking the code. Unfortunately, I did not solve the problem. I just ignored it.

Hi Mohamed,

I found the solution. You have to declare the int variable local that the textbox can access it.
Like var ii = i;

Here´s your fixed code, it should work with that:

@page "/test"

@for (var i = 0; i < _vms.Count; i++)
{
    var ii = i;
    <div class="row mt-2 align-items-center">
        <div class="col-md-3">
            <RadzenLabel Text="@_vms[ii].Type" />
        </div>
        <div class="col-md-3">
            <div Style="display: inline-flex; width: max-content; align-items: center;">
                <RadzenTextBox Name="SomeName"
                               @bind-Value="_vms[ii].Value" Style="width: 100%" Trim="true" />
            </div>
        </div>
    </div>
}

Hi Fabius,

Thanks alot. I appreciate it