# Blazor DropDownList, DropDownGrid and ListBox

URL: https://flexcoreui.com/demo/lists-dropdowns  
Section: Components  
Controls: DropDownListControl, DropDownGridControl, ListBoxControl  
Keywords: dropdown, dropdownlist, select, combobox, multi-column combobox, listbox, lookup grid, multiselect

Blazor dropdowns and list boxes: a plain or editable dropdown, a searchable multi-column lookup over 4,009 rows, and lists with checkboxes.

## Documentation

### Ddl

| Name | Type | Default | Description |
|---|---|---|---|
| DataSource | IEnumerable<TItem>? | null | The items. Enumerated again on each render for the options, the closed text and the automatic width. Null shows "No values" in the open list. |
| TextFieldName / ValueFieldName | string | "" | Names of the item properties that give each option its text and its value, read by reflection. Blank uses the item itself (a string) or its ToString(). |
| Value | TValue? | null | The current value. A value that matches no option shows as its own text; null or an empty string counts as no value. |
| Placeholder | string? | null | Gray text in the closed button, or the input's placeholder, while there is no value. Also counts toward the automatic width. |
| AriaLabel | string? | null | aria-label of the button or the editable input. |
| Width | string? | null | CSS width of the host. Unset: sized to the longest option text or the placeholder, 8 to 28 characters plus room for the arrow, never wider than the window less 24px. |
| PanelMaxHeight | int | 180 | Tallest open list in pixels before it scrolls. The visible space around the box can make it shorter. |
| PanelFitContentWidth | bool | false | Sizes the open list to its widest option (at most 360px or 90% of the window) instead of the box width. |
| CssClass | string? | null | Added to the host and to the button (or the editable input's wrapper). |
| Enabled | bool | true | False disables the button or input and closes an open list. |
| TabIndex | int? | null | tabindex of the button or input. Unset: the normal tab order, or -1 when the control is the editor of a hosted cell. |
| ItemTemplate | RenderFragment<TItem>? | null | Content of each option in the open list. The closed button and the editable input still show the TextFieldName text. |
| Editable | bool | false | Renders a text input instead of the button. Typed text is committed on Enter (and on blur, see below) and converted to TValue, whether or not it is in the list. |
| MaxLength | int? | null | maxlength of the editable input; a committed typed text longer than this is cut to it. |
| CommitEditableTextOnBlur | bool | true | Editable only: leaving the input commits the typed text. False commits on Enter only, and leaving a closed list puts back the committed text. |
| AutoFocus | bool | false | Focuses the button or input after the first render. |
| OpenOnRender | bool | false | Opens the list on the first render where this is true, once. |
| OpenOnArrowClickOnly | bool | false | Only a click on the arrow opens and closes the list; a click on the text does nothing. |
| OpenOnClickWhenClosed | bool | false | With OpenOnArrowClickOnly, a click on the text of a closed list still opens it; closing stays with the arrow, Escape, a pick or a click outside. |
| DelegateVerticalArrows | bool | false | Up and Down on a closed list go to OnKeyDown instead of changing the value. Needs an OnKeyDown handler. |
| SuppressUnchangedValueChange | bool | false | Picking the option that is already the value closes the list without raising ValueChanged or ValueChange. |
| AllowFiltering | bool | false | Declared but not read anywhere in the control: the list is never filtered. |
| ChildContent | RenderFragment? | null | Declared but never rendered. |

### Ddl events

| Name | Type | Description |
|---|---|---|
| ValueChanged | TValue? | The value changed: a pick from the list, a step on the closed list (Up, Down, Home, End or a typed letter), or committed typed text. Picking the current value again raises it too, unless SuppressUnchangedValueChange is set. |
| ValueChange | ChangeEventArgs<TValue, TItem> | Right after ValueChanged, with the new value and, for a pick or a step, the item. |
| TextChanged | string | Editable only: the text as the user types it, before it is committed (not while DelegateVerticalArrows is set). Value does not change. |
| Closed | none | The list closed without a choice: Escape, a click outside, a click on the arrow, or HidePopupAsync. Focus moving out of an open list raises it too, after taking an option highlighted with the keys. Choosing by click, Enter, Space or Tab does not. |
| EditableCommitted | none | Editable only: typed text was committed by Enter, Tab, leaving the box or a click outside, even when Value did not change. Not raised for a pick from the list. |
| OnKeyDown | KeyboardEventArgs | Keys the control passes on rather than handling, for hosts such as grid editors. In list mode: Tab, Left and Right, Escape on a closed list, Enter or Space after taking an option, and Up and Down on a closed list with DelegateVerticalArrows. With a handler set, Tab no longer takes the highlighted option. |

### Ddl args

| Name | Type | Description |
|---|---|---|
| Value | TVal? | The new value. |
| ItemData | TItm | The item behind it, for a pick or a step through the list; default when typed text was committed. |

### Ddl methods

| Name | Type | Description |
|---|---|---|
| FocusAsync() | Task | Focuses the editable input or the button. |
| ShowPopupAsync() | Task | Opens the list, if the control is enabled. |
| HidePopupAsync() | Task | Closes the list; raises Closed when it was open. |
| TryHandleHostKeyDownAsync(KeyboardEventArgs e) | Task<bool> | For a host that keeps focus while the list is open: Up, Down, Home and End move the highlight, Enter takes it, Escape closes. Returns false when the list is closed, a modifier key is down, or the key is another one. |

### Grid

| Name | Type | Default | Description |
|---|---|---|---|
| DataSource | IEnumerable<TItem>? | null | Rows for the popup grid. |
| Value | TValue? | null | The picked row's ValueFieldName value. A value that matches no row shows as its own text. |
| Columns | RenderFragment? | null | GridColumn elements for the popup grid. |
| ValueFieldName | string? | null | Property, matched ignoring case, whose value becomes Value, converted to TValue. Unset: the row itself, when it is a TValue. |
| ClosedTextFieldName | string? | null | Property shown in the closed box. Unset: TextFieldName. |
| TextFieldName | string? | null | Property shown in the closed box when ClosedTextFieldName is unset. Neither set: the row's ToString(). |
| Placeholder | string? | "Select an item..." | Shown in the closed box while there is no value. |
| ShowSearch | bool | true | A search box above the grid. It keeps the rows where the text of any public property contains the typed text, ignoring case, including properties with no column. Cleared when the popup closes. |
| SearchPlaceholder | string? | null | Placeholder of the search box; unset shows "Search...". |
| AllowClear | bool | true | A ✕ button in the box while there is a value. It sets Value to default and raises ValueChanged and OnSelectedItemChanged with default values. Hidden when Disabled or ReadOnly. |
| Disabled | bool | false | Disables and grays the box; the popup does not open. |
| ReadOnly | bool | false | The popup does not open and the clear button is hidden, but the box is not grayed. |
| Width | string? | "100%" | CSS width of the control. |
| PopupWidth | string? | "450px" | CSS width of the popup. Placement reads it as a number of pixels to keep the popup inside the window. |
| PopupHeight | string? | "240px" | Height of the grid area under the search box. |
| RowHeight | int | 22 | Row height of the popup grid in pixels. |
| AllowPaging | bool | false | Pages the popup grid. |
| PageSize | int | 10 | Rows per page when AllowPaging is on. |
| ShowColumnHeaders | bool | true | False hides the popup grid's header row; the column widths stay. |
| CssClass | string? | null | Added to the root fx-dropdown-grid element. |
| OpenOnRender | bool | false | Opens the popup on the first render where this is true, once. |
| AutoFocus | bool | false | Focuses the box after the first render. |

### Grid events

| Name | Type | Description |
|---|---|---|
| ValueChanged | TValue | A row was picked (a click, or Enter on the highlighted row) or the clear button was pressed. |
| OnSelectedItemChanged | TItem? | Right after ValueChanged: the picked row, or null after a clear. |
| Closed | none | The popup closed: a pick, Escape, a click outside or on the box, or the clear button while it was open. Escape on a closed box raises it too, so a cell editor can dismiss itself. |

### List

| Name | Type | Default | Description |
|---|---|---|---|
| DataSource | IEnumerable<TItem>? | null | Items, one row each. |
| TextField / ValueField | string | "" | Names of the item properties that give each row its label and its value, read by reflection. Blank gives an empty string, so plain strings need wrapping in a record. |
| Value | List<string>? | null | The selected values, compared ignoring case. Read again on every parameter update, so a new list from the page replaces the selection. |
| SelectionMode | ListBoxSelectionMode | ListBoxSelectionMode.Single | Single keeps at most one value; Multiple keeps any number. |
| ShowCheckbox | bool | false | Single mode only: checkboxes instead of radio buttons, so the one choice can be unchecked. Multiple mode always draws checkboxes. |
| CssClass | string? | null | Added to the fx-listbox element. |

### List events

| Name | Type | Description |
|---|---|---|
| ValueChanged | List<string> | When a checkbox is checked or unchecked, or a radio button chosen: a new list of the selected values, in no guaranteed order. In single mode it holds at most one value. |

### Modes

| Name | Description |
|---|---|
| Single | At most one value: radio buttons sharing one group name per list, or, with ShowCheckbox, checkboxes where checking one unchecks the other. |
| Multiple | Any number of values; each row is a checkbox. |

### Css

| Name | Description |
|---|---|
| fx-dropdown-host | The dropdown's outer element: inline-block, at least 80px wide, Tahoma at 10px times --fx-zoom. fx-dropdown-open-up is added while the list opens upward. |
| fx-dropdown · fx-dropdown-editable · disabled | The closed button, or the editable input's wrapper: 20px high with a 1px blue-gray border and a dotted focus outline; gray when disabled. |
| fx-dropdown-text · fx-dropdown-placeholder · fx-dropdown-input · fx-dropdown-arrow | The button's text and its gray placeholder state, the editable text input, and the 18px arrow lane. |
| fx-dropdown-panel · fx-dropdown-panel-fit | The open list, positioned under the box, 180px at most by default; the fit variant takes its widest option's width. |
| fx-dropdown-option · highlighted · selected | An option button. highlighted (white on blue) follows the mouse and the keys; selected marks the current value and adds no color. |
| fx-dropdown-empty | "No values" in the open list when DataSource is null. |
| fx-dropdown-backdrop | A transparent full-window button behind the open list; a click on it closes the list. |
| fx-dropdown-legacy-blue | Pass it as CssClass for a white-on-blue button and list. |
| fx-dropdown-grid · fx-open · fx-disabled | The lookup's root element, with its state while the popup is open and when Disabled. |
| fx-dropdown-grid-input-wrap · fx-dropdown-grid-input · fx-dropdown-grid-arrow · fx-dropdown-grid-clear-btn | The closed box: its wrapper, the read-only input (13px times --fx-zoom), the arrow lane and the ✕ button. |
| fx-dropdown-grid-popup · fx-dropdown-grid-headerless | The popup, white with a rounded border and a shadow; the headerless variant collapses the grid's header row. |
| fx-dropdown-grid-search-bar · fx-dropdown-grid-search-input · fx-dropdown-grid-body | The search row, its input, and the area that holds the grid. |
| fx-dropdown-grid-backdrop | The popup's transparent full-window backdrop; a click on it closes the popup. |
| fx-listbox · fx-listbox-item | The list box, a column with 6px gaps that scrolls past 320px, and each label row with its input. |

### Keys list

| Name | Description |
|---|---|
| Enter, Space, F4, Alt+Down (closed) | Opens the list with the current value highlighted, or the first option when there is none. |
| Enter, Space (open) | Takes the highlighted option, closes the list and returns focus to the button. |
| Up / Down | Closed: selects the previous or next option at once. Open: moves the highlight. Both stop at the ends. |
| Home / End | The same for the first or last option. |
| A printable character | Goes to the first option whose text, or value, starts with the typed characters; typing again within a second extends them, and repeating one character cycles through its matches. Closed: selects it. Open: highlights it. |
| Escape | Closes the list without changing the value. |
| Tab (open) | Takes the highlighted option; focus stays on the dropdown. |

### Keys grid

| Name | Description |
|---|---|
| Down | Closed: opens the popup with the current value's row highlighted, or the first row. Open: highlights the next row. |
| Up (open) | Highlights the previous row. |
| Enter | Closed: opens the popup. Open: picks the highlighted row. |
| Escape | Closes the popup without picking. |

## Examples

### Dropdown

```razor
@using Fx.ControlKit

<div class="ld">
    <div class="pair">
        <div class="field">
            <span class="field-label">Destination</span>
            <DropDownListControl TValue="string" TItem="Destination" DataSource="@_destinations" TextFieldName="City" ValueFieldName="City"
                                 @bind-Value="_city" ValueChange="args => _picked = args.ItemData" Placeholder="Choose a destination"
                                 Width="220px" Enabled="@(!_sent)" AriaLabel="Destination">
                <ItemTemplate Context="d"><span>@d.City</span> <span class="muted">@d.Country</span></ItemTemplate>
            </DropDownListControl>
        </div>
        <div class="field">
            <span class="field-label">Flying from</span>
            <DropDownListControl TValue="string" TItem="string" DataSource="@_gateways" @bind-Value="_from" Editable="true"
                                 Placeholder="Pick or type a city" Width="220px" Enabled="@(!_sent)" AriaLabel="Flying from" />
        </div>
        <div class="switch-cell">
            <SwitchControl @bind-Checked="_sent" Label="Quote sent" />
        </div>
    </div>
    <p class="quote" role="status">
        <strong>Quote for Hermione Ranger</strong>
        <span>@(_picked is null ? "No destination yet" : $"{_picked.City}, {_picked.Country} ({_picked.Region})"), flying from @(string.IsNullOrWhiteSpace(_from) ? "a city still to choose" : _from)</span>
        <span>@(_sent ? "Sent to the traveler: the fields are locked." : "Draft: both fields can still change.")</span>
    </p>
</div>
```

```csharp
// Destination dropdown
private string? _city;
private Destination? _picked;
private readonly string[] _gateways = { "Amsterdam", "Chicago", "Dublin", "Frankfurt", "London", "New York", "Singapore", "Toronto" };
private string? _from = "London";
private bool _sent;

// Destinations (the dropdown)
private sealed record Destination(string City, string Region, string Country);
private static readonly Destination[] _destinations =
    TravelData.Destinations.Select(d => new Destination(d.City, d.Region, d.Country)).ToArray();
```

### Lookup

```razor
@using Fx.ControlKit.Grid

<div class="ld">
    <div class="pair">
        <div class="lookup">
            <span class="field-label">Flying from</span>
            <div class="lookup-box">
                <DropDownGridControl TItem="Airport" TValue="string" DataSource="@AirportData.Airports" @bind-Value="_fromCode"
                                     ValueFieldName="Code" ClosedTextFieldName="Label" Placeholder="Choose an airport"
                                     SearchPlaceholder="Code, city, country or name" PopupWidth="560px" PopupHeight="260px" RowHeight="24">
                    <Columns>
                        <GridColumn Field="Code" HeaderText="Code" Width="60px" />
                        <GridColumn Field="Name" HeaderText="Airport" Width="230px" />
                        <GridColumn Field="City" HeaderText="City" Width="120px" />
                        <GridColumn Field="Country" HeaderText="Country" Width="130px" />
                    </Columns>
                </DropDownGridControl>
            </div>
        </div>
        <div class="lookup">
            <span class="field-label">Flying to</span>
            <div class="lookup-box">
                <DropDownGridControl TItem="Airport" TValue="string" DataSource="@AirportData.Airports" @bind-Value="_toCode"
                                     ValueFieldName="Code" ClosedTextFieldName="Label" Placeholder="Choose an airport"
                                     SearchPlaceholder="Code, city, country or name" PopupWidth="560px" PopupHeight="260px" RowHeight="24">
                    <Columns>
                        <GridColumn Field="Code" HeaderText="Code" Width="60px" />
                        <GridColumn Field="Name" HeaderText="Airport" Width="230px" />
                        <GridColumn Field="City" HeaderText="City" Width="120px" />
                        <GridColumn Field="Country" HeaderText="Country" Width="130px" />
                    </Columns>
                </DropDownGridControl>
            </div>
        </div>
    </div>
    @if (Find(_fromCode) is { } from && Find(_toCode) is { } to)
    {
        <p class="result"><strong>@from.Code → @to.Code</strong>: @from.Name, @from.Country to @to.Name, @to.Country.
            Great-circle distance <strong>@Kilometers(from, to).ToString("N0") km</strong> (@((Kilometers(from, to) / 1.609344).ToString("N0")) miles).</p>
    }
    else
    {
        <p class="result">Pick both airports for the distance: from <strong>@(_fromCode ?? "no airport yet")</strong>, to <strong>@(_toCode ?? "no airport yet")</strong>.</p>
    }
</div>
```

```csharp
// Airport lookups: the OurAirports snapshot from Data/AirportData.cs; the values are airport codes
private string? _fromCode = "LHR";
private string? _toCode = "NAP";
private static readonly Dictionary<string, Airport> _airportsByCode = AirportData.Airports.ToDictionary(a => a.Code);
private static Airport? Find(string? code) => code is not null && _airportsByCode.TryGetValue(code, out var airport) ? airport : null;

// Great-circle distance on a sphere of radius 6,371 km (the haversine formula)
private static double Kilometers(Airport a, Airport b)
{
    static double Radians(double degrees) => degrees * Math.PI / 180;
    var dLat = Radians(b.Latitude - a.Latitude);
    var dLon = Radians(b.Longitude - a.Longitude);
    var h = Math.Pow(Math.Sin(dLat / 2), 2) + Math.Cos(Radians(a.Latitude)) * Math.Cos(Radians(b.Latitude)) * Math.Pow(Math.Sin(dLon / 2), 2);
    return 2 * 6371 * Math.Asin(Math.Sqrt(h));
}
```

### Listbox

```razor
@using Fx.ControlKit

<div class="ld">
    <div class="pair">
        <div>
            <p class="pane-title" id="going-title">Who is going to Amalfi</p>
            <div role="group" aria-labelledby="going-title">
                <ListBoxControl TItem="Traveler" DataSource="@_travelers" TextField="Name" ValueField="Name"
                                SelectionMode="ListBoxSelectionMode.Multiple" Value="_going" ValueChanged="GoingChanged" CssClass="two-columns" />
            </div>
            <div class="actions">
                <ButtonControl CssClass="btn-sm" OnClick="() => GoingChanged(new())" Disabled="@(_going.Count == 0)">Clear the travelers</ButtonControl>
            </div>
        </div>
        <div>
            <p class="pane-title" id="lead-title">Lead traveler</p>
            <div role="group" aria-labelledby="lead-title">
                <ListBoxControl TItem="Traveler" DataSource="@Going" TextField="Name" ValueField="Name"
                                ShowCheckbox="_leadBoxes" @bind-Value="_lead" />
            </div>
            <div class="switch-row">
                <SwitchControl @bind-Checked="_leadBoxes" Label="Check boxes on this list" />
            </div>
        </div>
    </div>
    <p class="result" role="status">
        @if (_going.Count == 0)
        {
            <span>Nobody going yet</span>
        }
        else
        {
            <span>@_going.Count going: <strong>@string.Join(", ", _going)</strong></span>
        }
        · Lead traveler: <strong>@(_lead.FirstOrDefault() ?? "nobody yet")</strong>
    </p>
</div>
```

```csharp
// List boxes: the second list holds only the travelers checked in the first
private sealed record Traveler(string Name);
private static readonly Traveler[] _travelers =
{
    new("Albus Door"), new("Hermione Ranger"), new("Ron Measly"), new("Luna Goodlove"), new("Neville Longbutton"), new("Ginny Measly"),
};
private List<string> _going = new() { "Albus Door", "Hermione Ranger" };
private List<string> _lead = new() { "Hermione Ranger" };
private bool _leadBoxes;
private IEnumerable<Traveler> Going => _travelers.Where(t => _going.Contains(t.Name));
private void GoingChanged(List<string> going)
{
    _going = going;
    _lead = _lead.Where(going.Contains).ToList();   // a lead who is no longer going is dropped
}
```

