Home > database >  How to add dynamic checkboxes in a Blazor-server app that use a list of booleans?
How to add dynamic checkboxes in a Blazor-server app that use a list of booleans?

Time:01-02

To clarify my question more I'll first show you add a checkbox using the blazor component library I'm using:

<MudCheckBox @bind-Checked="@Basic_CheckBox1"></MudCheckBox>
@code{
public bool Basic_CheckBox1 { get; set; } = false;
}

the code above creates a checkbox and then toggles the boolean Basic_CheckBox1 to true or false based on if the checkbox is checked or not. here is my code

 @for (int i = 0; i < checkboxNames.Count; i  )
        {

            <MudCheckBox @bind-Checked="@checkboxBools[i]" Label="@checkboxNames[i]"></MudCheckBox>
        }

this code works until I check or uncheck my created checkboxes, then I get the index out of range error, how can I fix this? I need to use a list of booleans because I don't know how many checkboxes I will need until runtime, if there is any other solution please let me know.

CodePudding user response:

Think of it like the bind isn't done there and then in the loop, but later. By the time the bind comes to be done, the value of i is off the end of the array Length, having been incremented repeatedly. Instead, you can save the current value of your loop variable i into another variable, then use that other variable in your bind:

    @for (int i = 0; i < checkboxNames.Length; i  )
    {
        var x = i;
        <MudCheckBox @bind-Checked="@checkboxBools[x]" Label="@checkboxNames[i]"></MudCheckBox>
    }

checkBoxBools should be an array/list that is the same length (initalized to have the same number of elements as) checkBoxNames.. For example:

    string[] checkboxNames = new string[]{"a","b","c"};
    bool[] checkboxBools = new bool[3];

Or, if something else is providing a variable number of names:

    checkboxNames = context.People.Select(p => p.Name).ToArray();
    checkboxBools = new bool[checkBoxNames.Length];

https://try.mudblazor.com/snippet/GamQEFuFIwdRbzEx

  • Related