# ListBox Selection with CheckBoxes

## Environment

<table>
    <tbody>
        <tr>
            <td>Product</td>
            <td>ListBox for Blazor</td>
        </tr>
    </tbody>
</table>

## Description

This KB article answers the following questions:

* How to select ListBox items with checkboxes?
* Does the ListBox support single and multiple checkbox selection?
* How to implement a checkbox multi select demo with the Blazor ListBox?

## Solution

1. Define a [ListBox item template](https://www.telerik.com/blazor-ui/documentation/components/listbox/templates#item-template).
2. In the `<ItemTemplate>`, add a [CheckBox component](https://www.telerik.com/blazor-ui/documentation/components/checkbox/overview) with a [`Value` parameter](https://www.telerik.com/blazor-ui/documentation/components/checkbox/overview#checkbox-parameters) and a [`ValueChanged` event handler](https://www.telerik.com/blazor-ui/documentation/components/checkbox/events#valuechanged).
3. The CheckBox `Value` must be `true` if the current item (`ItemTemplate` `context`) is a member of the ListBox `SelectedItems` collection.
4. The CheckBox `ValueChanged` handler must add or remove the current ListBox item from the `SelectedItems` collection.
5. Wrap the CheckBox component in a `<span @onclick:stopPropagation>`, so that the checkbox clicks do not interfere with the built-in ListBox selection feature.
6. (optional) Use the [ListBox `SelectedItemsChanged` event](https://www.telerik.com/blazor-ui/documentation/components/listbox/events#selecteditemschanged) to toggle item selection without the need to hold the `Ctrl` key.
7. (optional) Apply some padding on the `<span>` element, so that if the user clicks near the checkbox, but outside it, the ListBox `SelectedItems` collection doesn't reset to a single item.

> caption Using checkboxes for ListBox selection

```RAZOR
ListBox <code>SelectionMode</code>:

<TelerikRadioGroup Data="@RadioGroupData"
                   @bind-Value="@RadioGroupValue"
                   Layout="@RadioGroupLayout.Horizontal"
                   OnChange="@((object currentValue) => ListBoxSelectedItems = new List<ListBoxModel>())" />

<br />

<label class="k-checkbox-label">
    <TelerikCheckBox @bind-Value="@ShouldSelectWithoutCtrl" />
    Item Text Click Toggles Selection Without <strong>Ctrl</strong> Key
</label>

<br />
<br />

<TelerikListBox @ref="@ListBoxRef"
                Data="@ListBoxData"
                TItem="@ListBoxModel"
                TextField="@nameof(ListBoxModel.Name)"
                SelectionMode="@RadioGroupValue"
                SelectedItems="@ListBoxSelectedItems"
                SelectedItemsChanged="@ListBoxSelectedItemsChanged"
                OnReorder="@OnListBoxReorder"
                Width="240px"
                Height="auto">
    <ListBoxToolBarSettings>
        <ListBoxToolBar>
            <ListBoxToolBarMoveUpTool />
            <ListBoxToolBarMoveDownTool />
        </ListBoxToolBar>
    </ListBoxToolBarSettings>
    <ItemTemplate>
        <span @onclick:stopPropagation class="checkbox-wrapper">
            <TelerikCheckBox Value="@( ListBoxSelectedItems.Contains(context) )"
                             ValueChanged="@( (bool newValue) => OnItemCheckBoxValueChanged(newValue, context) )" />
        </span>
        @context.Name
    </ItemTemplate>
</TelerikListBox>

<style>
    .checkbox-wrapper {
        padding: 0 .4em;
    }
</style>

@code {
    private TelerikListBox<ListBoxModel> ListBoxRef { get; set; } = null!;

    private List<ListBoxModel> ListBoxData { get; set; } = new List<ListBoxModel>();

    private IEnumerable<ListBoxModel> ListBoxSelectedItems { get; set; } = new List<ListBoxModel>();

    private List<ListBoxSelectionMode> RadioGroupData { get; set; } = new List<ListBoxSelectionMode>() {
        ListBoxSelectionMode.Single,
        ListBoxSelectionMode.Multiple
    };

    private ListBoxSelectionMode RadioGroupValue { get; set; } = ListBoxSelectionMode.Multiple;
    private bool ShouldSelectWithoutCtrl { get; set; } = true;

    private void ListBoxSelectedItemsChanged(IEnumerable<ListBoxModel> newSelectedItems)
    {
        if (RadioGroupValue == ListBoxSelectionMode.Single || !ShouldSelectWithoutCtrl)
        {
            ListBoxSelectedItems = newSelectedItems;
            return;
        }

        if (newSelectedItems.Count() == 1 && ListBoxSelectedItems.Count() > 0)
        {
            if (!ListBoxSelectedItems.Contains(newSelectedItems.First()))
            {
                ((List<ListBoxModel>)ListBoxSelectedItems).AddRange(newSelectedItems);
            }
            else
            {
                ((List<ListBoxModel>)ListBoxSelectedItems).RemoveAll(x => newSelectedItems.Contains(x));
            }
        }
        else
        {
            ListBoxSelectedItems = newSelectedItems;
        }
    }

    private void OnItemCheckBoxValueChanged(bool newValue, ListBoxModel item)
    {
        var currentSelection = new List<ListBoxModel>(ListBoxSelectedItems);

        if (newValue)
        {
            if (RadioGroupValue == ListBoxSelectionMode.Multiple)
            {
                currentSelection.Add(item);
            }

            else
            {
                currentSelection = new List<ListBoxModel>() { item };
            }
        }
        else
        {
            currentSelection.Remove(item);
        }

        ListBoxSelectedItems = currentSelection;
    }

    private void OnListBoxReorder(ListBoxReorderEventArgs<ListBoxModel> args)
    {
        ListBoxData.RemoveAll(x => args.Items.Contains(x));
        ListBoxData.InsertRange(args.ToIndex, args.Items);

        ListBoxRef.Rebind();
    }

    protected override void OnInitialized()
    {
        for (int i = 1; i <= 7; i++)
        {
            ListBoxData.Add(new ListBoxModel()
            {
                Id = i,
                Name = $"ListBox Item {i}",
            });
        }
    }

    public class ListBoxModel
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
    }
}
```

## See Also

* [ListBox Templates](https://www.telerik.com/blazor-ui/documentation/components/listbox/templates)
* [ListBox Selection](https://www.telerik.com/blazor-ui/documentation/components/listbox/selection)
