DxComboBox<TData, TValue> Class
A text box editor with an integrated multi-column dropdown list that supports item filtering and virtual scrolling.
Namespace: DevExpress.Blazor
Assembly: DevExpress.Blazor.v23.2.dll
NuGet Package: DevExpress.Blazor
Declaration
public class DxComboBox<TData, TValue> :
DxComboBoxBase<TData, TValue>,
IFilteringComponent,
IRequireSelfCascading,
IDataSourceSettings<TData>,
IServiceProviderAccessor,
IEditorSettingsAccessor,
IFocusableEditor,
IDropDownOwner
Type Parameters
Name | Description |
---|---|
TData | The data item type. |
TValue | The value type. |
Remarks
The DevExpress ComboBox for Blazor (<DxComboBox>
) component displays a drop-down window with a list of items. Users can click an item in the drop-down list or use the Up arrow, Down arrow, and Enter keys to navigate between items and select them. When a user presses and holds an arrow key, the editor’s window continuously navigates between items.
Add a ComboBox to a Project
Follow the steps below to add the ComboBox component to an application:
- Use a DevExpress Project Template to create a new Blazor Server or Blazor WebAssembly application. If you use a Microsoft project template or already have a Blazor project, configure your project to incorporate DevExpress Blazor components.
- Add the
<DxComboBox>
…</DxComboBox>
markup to a.razor
file. - Bind the component to data.
- Configure the component: add a clear button and placeholder, customize appearance, specify the filter mode, and so on (see the sections below).
Bind to Data
Strongly Typed Collection
Use the Data property to bind the ComboBox to a strongly typed collection or enumeration. Initialize this object in the OnInitialized lifecycle method or before this method is invoked. Use the DataAsync property instead of the Data
property if a strongly typed collection is loaded asynchronously (for instance, from an HTTP request).
Use the Value property to specify the component’s selected value or item. You can use the @bind attribute to bind the Value
property to a data field. For more information, refer to the following help topic: Two-Way Data Binding.
<DxComboBox Data="@Cities" @bind-Value="@Value" ></DxComboBox>
@code {
IEnumerable<string> Cities = new List<string>() {
"London",
"Berlin",
"Paris",
};
string Value { get; set; }
}
The ComboBox can detect IQueryable<T> collections and use benefits of the corresponding LINQ query providers (such as Entity Framework).
Custom Object Collection
You can bind the ComboBox to a data collection (Data
) that stores custom objects (IEnumerable<CustomType>
). The Value
property can also contain a custom object. In this case, you need to override the custom object’s Equals method. Otherwise, the ComboBox uses the default Equals
method implementation to compare items in the Data
collection and the Value
item. This method determines whether two object instances are equal. The compared items will not be equal if they are different instances (even if they have exactly the same properties). As a result, the component will not display a selected item.
You also need to set the TextFieldName property. It specifies the custom object’s field name that returns strings to be shown in the ComboBox drop-down window. If the TextFieldName
property is not specified, the ComboBox component searches for a Text field in the data source and uses this field as a text field. Otherwise, the ComboBox is populated with CustomType.ToString() values.
@using BlazorApp.Data
<DxComboBox Data="@Staff.DataSource"
TextFieldName="@nameof(Person.Text)"
@bind-Value="@Value"
AllowUserInput="true">
</DxComboBox>
@code {
Person Value { get; set; } = Staff.DataSource[0];
}
Otherwise, the ComboBox items are populated with CustomType.ToString()
values.
Load Custom Data
When you bind an editor to data from a Web API service, assign the data type to the component’s T
parameter and use the CustomData property to implement custom data load logic.
You can also enable Virtual Scrolling to improve client-side performance.
Items
The <DxComboBox>
drop-down window displays a list of predefined items. Set the AllowUserInput property to true
to allow users to type values into the ComboBox’s edit box.
<DxComboBox Data="@Cities"
AllowUserInput="true"
NullText="Select City ..."
@bind-Value="@Value"
@bind-Text="@Text">
</DxComboBox>
@code {
IEnumerable<string> Cities = new List<string>() {
"London",
"Berlin",
"Paris",
};
string Text { get; set; } = "New York";
string Value { get; set; }
}
Use the Text property to specify an editor value in code. To respond to an editor’s text change, handle the TextChanged event.
The table below lists API members related to the ComboBox item collection:
Member | Description |
---|---|
Specifies the ComboBox’s selected value/item. | |
Fires when the ComboBox’s selected value changes. | |
Specifies the data source field that populates values for the ComboBox’s items. | |
Specifies a template used to display the ComboBox’s items. | |
Specifies the current state (displayed/hidden) of a drop-down window. | |
Displays an editor’s drop-down window. |
Clear Button and Placeholder
Set the ClearButtonDisplayMode property to Auto
to show the Clear button when the editor has a non-null value. Users can click this button to clear the editor’s value (set it to null
).
Use the NullText property to display the prompt text (placeholder) in the editor when its value is null
.
<DxComboBox NullText="Select a country..."
Data="@CountryData.Countries"
@bind-Value="@CurrentCountry"
TextFieldName="@nameof(Country.CountryName)"
ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
</DxComboBox>
@code {
Country CurrentCountry { get; set; } = CountryData.Countries[1];
}
Note
If you use the EditBoxTemplate property and need to show the clear button and placeholder, you should also add a DxInputBox object to the template markup.
Cascading Comboboxes
The <DxComboBox>
allows you to create cascade lists - populate one ComboBox with items based on the user selection from another ComboBox. Use the Value property to access the selected item. To respond to the selected item change, handle the ValueChanged event.
@using CountryCityData
<DxComboBox Data="@Countries"
TextFieldName="@nameof(Country.CountryName)"
Value="@CurrentCountry"
ValueChanged="@((Country country) => SelectedCountryChanged(country))"
AllowUserInput="true">
</DxComboBox>
<DxComboBox Data="@CurrentCountryCities"
TextFieldName="@nameof(City.CityName)"
@bind-Value="@CurrentCity"
AllowUserInput="true">
</DxComboBox>
@code {
List<Country> Countries { get; set; } = CountryData.Countries;
List<City> CurrentCountryCities { get; set; } = new List<City>();
Country CurrentCountry { get; set; } = CountryData.Countries[1];
City CurrentCity { get; set; } = CityData.Cities[4];
protected override void OnInitialized() {
base.OnInitialized();
SelectedCountryChanged(CurrentCountry);
}
void SelectedCountryChanged(Country country) {
CurrentCountry = country;
CurrentCountryCities = CityData.Cities.FindAll(city => city.CountryId == CurrentCountry.Id);
CurrentCity = CurrentCountryCities[0];
}
}
Filter Data
<DxComboBox>
allows you to dynamically filter list items based on the text typed into the editor. Use the FilteringMode property to enable filtering and specify the filter mode (Contains
or StartsWith
).
<DxComboBox FilteringMode="DataGridFilteringMode.Contains" Data="@Data" @bind-Value="@Value"></DxComboBox>
@code {
IEnumerable<Country> Data;
Country Value { get; set; }
}
The ComboBox automatically highlights the first match in the filtered list. Users can press the Enter key to select the value.
Note
If you use the EditBoxTemplate property and need to enable filter mode, you should add a DxInputBox object to the template markup.
Multiple Columns
The ComboBox control can display data across multiple columns. Follow the steps below to create columns:
- Add a
<Columns>
tag to the component’s markup to declare the column collection. Populate the
Columns
collection with DxListEditorColumn objects. These objects include the following properties:- FieldName - Specifies the data source field that populates column items.
- Caption - Specifies the column header.
- Visible - Specifies column visibility.
- VisibleIndex - Specifies column position.
- Width - Specifies column width.
To format an edit box’s value, use the EditFormat property.
@using StaffData
<DxComboBox Data="@Staff.DataSource"
@bind-Value="@SelectedPerson"
EditFormat ="{1} {2}">
<Columns>
<DxListEditorColumn FieldName="Id" Width="50px" />
<DxListEditorColumn FieldName="FirstName" Caption="Name"/>
<DxListEditorColumn FieldName="LastName" Caption="Surname"/>
</Columns>
</DxComboBox>
@code {
Person SelectedPerson { get; set; } = Staff.DataSource[0];
}
Customization
The ComboBox component allows you to customize its appearance and the appearance of its items.
Appearance Customization
Use the SizeMode property to specify the size of a ComboBox. The code below applies different sizes to ComboBox components.
<DxComboBox Data="@Cities"
NullText="Select City ..."
@bind-Value="@Value"
SizeMode="SizeMode.Small">
</DxComboBox>
<DxComboBox Data="@Cities"
NullText="Select City ..."
@bind-Value="@Value"
SizeMode="SizeMode.Medium">
</DxComboBox>
<DxComboBox Data="@Cities"
NullText="Select City ..."
@bind-Value="@Value"
SizeMode="SizeMode.Large">
</DxComboBox>
@code {
IEnumerable<string> Cities = new List<string>() {
"London",
"Berlin",
"Paris",
};
string Value { get; set; }
}
To customize ComboBox input, use the InputCssClass property. The following code snippet applies a custom style to input borders:
<style>
.my-style {
border: 2px dotted orange;
}
</style>
<DxComboBox Data="@Cities"
NullText="Select City ..."
@bind-Value="@Value"
InputCssClass="my-style">
</DxComboBox>
@code {
IEnumerable<string> Cities = new List<string> () {
"London",
"Berlin",
"Paris",
};
string Value { get; set; }
}
For more information, refer to the following help topics:
Items Customization
The ItemTemplate property allows you to customize the appearance of the ComboBox’s items. Use the template’s context
parameter to access a data object and its fields (for instance, you can get the value of a data field).
The example below demonstrates how to display the ComboBox’s items in a card-like view. Each item shows an employee’s first name, last name, photo, and phone number.
@inject NwindDataService NwindDataService
<DxComboBox Data="@Data"
@bind-Value="@Value"
CssClass="cw-480">
<ItemTemplate>
<div class="combobox-item-template">
<img src="@StaticAssetUtils.GetImagePath(GetImageFileName(context))" />
<div class="combobox-item-template-text">
<span>@context.FirstName @context.LastName</span>
<span class="combobox-item-template-employee-phone">@context.HomePhone</span>
</div>
</div>
</ItemTemplate>
</DxComboBox>
@code {
IEnumerable<Employee> Data { get; set; }
Employee Value { get; set; }
protected override async Task OnInitializedAsync() {
Data = await NwindDataService.GetEmployeesAsync();
Value = Data.FirstOrDefault();
}
string GetImageFileName(Employee employee) {
return $"employees/item-template{employee.EmployeeId}.jpg";
}
}
Edit Box Customization
The EditBoxTemplate property allows you to customize the appearance of a ComboBox item displayed in the edit box. It can be the selected item or focused item when a user tries to select it.
The most popular usage scenario for the EditBoxTemplate
property is to show item icons in the edit box.
<DxComboBox Data="@Items"
@bind-Value="@Value"
CssClass="cw-480" >
<EditBoxTemplate>
@GetTemplateContent(context)
</EditBoxTemplate>
...
</DxComboBox>
@code {
string Value { get; set; } = "Low";
IEnumerable<string> Items = new List<string>() {"Low", "Normal", "High"};
RenderFragment GetTemplateContent(string item) {
return @<div class="template-container">
<svg class="@GetIconCssClass(item)" role="img">
<use href="@GetIconHref(item)"/>
</svg>
@item
</div>;
}
string GetIconHref(string item) {
return item != null ? StaticAssetUtils.GetImagePath($"icons/levels.svg#dx-{item.ToLower()}-level") : string.Empty;
}
string GetIconCssClass(string item) {
var cssClass = "template-icon";
if (item != null)
cssClass += $" {item.ToLower()}-level";
return cssClass;
}
}
You can also create an edit box template that supports user input and filter mode:
- Add
<EditBoxTemplate>
…</EditBoxTemplate>
to the ComboBox markup. - Declare a DxInputBox object within the
EditBoxTemplate
markup. - Use the
DxComboBox
‘s InputCssClass to customize input box appearance. - Optional. Set the DxComboBox.AllowUserInput to
true
. - Optional. Use the DxComboBox.FilteringMode property to enable filter mode.
- Optional. Use the NullText property to display the prompt text in the edit box when the editor’s Value is
null
.
<DxComboBox Data="@Cities"
@bind-Value="@CurrentCity"
AllowUserInput="true"
FilteringMode="DataGridFilteringMode.StartsWith"
NullText="Select City ..."
ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto">
<EditBoxTemplate>
@if (context != null) {
<span style="white-space: pre;">Selected City: </span>
}
<DxInputBox/>
</EditBoxTemplate>
</DxComboBox>
@code {
string CurrentCity { get; set; } = "London";
IEnumerable<string> Cities = new List<string>() { "New York", "London", "Berlin", "Paris" };
}
Hide Built-In Drop-Down Button
Set the ShowDropDownButton property to false
to hide the built-in button that invokes a drop-down menu. If you need a custom button, you can add a new command button.
Add Command Buttons
You can add custom command buttons to the ComboBox. Refer to Command Buttons for more information.
The code below adds the Add Employee button to the ComboBox.
<DxComboBox Data="@Data"
TextFieldName="@nameof(Employee.Text)"
@bind-Value="@SelectedEmployee"
CssClass="dx-demo-editor-width">
<Buttons>
<DxEditorButton IconCssClass="editor-icon editor-icon-add"
Tooltip="Add an employee"
Click="@(_ => OnButtonClick())" />
</Buttons>
</DxComboBox>
@code{
IObserver<string> toasterRef;
IEnumerable<Employee> Data { get; set; }
Employee SelectedEmployee { get; set; }
bool AddEmployeePopupVisible { get; set; }
protected override async Task OnInitializedAsync() {
Data = await NwindDataService.GetEmployeesAsync();
SelectedEmployee = Data.FirstOrDefault();
}
void OnButtonClick() {
AddEmployeePopupVisible = true;
}
void OnEmployeeAdded(Employee newEmployee) {
AddEmployeePopupVisible = false;
if (newEmployee != null) {
Data = Data.Append(newEmployee);
}
}
}
Virtual Scrolling
When virtual scrolling is activated (ListRenderMode is set to Virtual
), the ComboBox renders data on demand when a user scrolls its items.
<DxComboBox ListRenderMode="ListRenderMode.Virtual"
Data="@Strings"
@bind-Value="@Value" >
</DxComboBox>
Input Validation
You can add a standalone ComboBox or Form Layout component to Blazor’s standard EditForm. This form validates user input based on data annotation attributes defined in a model and indicates errors. To specify which ComboBox property takes part in input validation (Text or Value), use the ValidateBy property. If you handle the ValueChanged
event and cannot use two-way binding, specify the ValueExpression property to identify the value passed to the event handler.
<EditForm Model="@starship" Context="EditFormContext">
<DataAnnotationsValidator />
<DxFormLayout >
<DxFormLayoutItem Caption="Primary Classification:" ColSpanMd="6" >
<Template >
<DxComboBox
NullText="Select classification ..."
ClearButtonDisplayMode="DataEditorClearButtonDisplayMode.Auto"
@bind-Value="@starship.Classification"
Data="@(new List<string>() { "Defense", "Exploration", "Diplomacy" })"
ValidateBy="ComboBoxValidateBy.Value"
/>
</Template >
</DxFormLayoutItem >
@*...*@
</DxFormLayout>
</EditForm>
@code {
private Starship starship=new Starship();
}
For more information, refer to the following help topic: Validate Input.
Read-Only State
<DxComboBox>
supports a read-only state. Set the ReadOnly property to true
to activate this option.
<DxComboBox ReadOnly="true"
Data="@Strings"
@bind-Value="@Value" >
</DxComboBox>
Drop-Down Window Width
Use the DropDownWidthMode property to specify the width of the drop-down list. The following values are available:
ContentOrEditorWidth (Default) - The list displays item text completely. The minimum list width matches the editor.
ContentWidth - The list width is equal to the width of the longest list item.
EditorWidth - The list width matches the editor. List items are cut if they do not fit.
Note
When the ComboBox renders items on demand (ListRenderMode is set to Virtual
), the list width can change while users scroll items.
The following code sets the width of the drop-down list to the editor width.
@using BlazorApp.Data
<DxComboBox Data="@Staff.DataSource"
@bind-Value="@Value"
TextFieldName="@nameof(Person.Text)"
DropDownWidthMode="DropDownWidthMode.EditorWidth">
</DxComboBox>
@code {
Person Value { get; set; } = Staff.DataSource[0];
}
Drop-Down Window Direction
Use the DropDownDirection property to specify the direction in which the ComboBox’s drop-down window is displayed relative to the input element. The default value is Down
. The following code changes the direction to Up
:
<DxComboBox Data="@Cities"
@bind-Value="@Value"
NullText="Select City ..."
DropDownDirection="DropDownDirection.Up">
</DxComboBox>
@code {
IEnumerable<string> Cities = new List<string>() {
"London",
"Berlin",
"Paris",
};
string Value { get; set; }
}
Note
If the editor is close to a browser window’s edge and there is not enough space to display the drop-down window in the specified direction, the drop-down window is displayed in the opposite direction.
HTML Attributes and Events
You can use HTML attributes and events to configure the ComboBox.
<DxComboBox Data="@Strings"
@bind-Value="@Value"
maxlength="10"
@onclick="MyFunction">
</DxComboBox>
@code {
void MyFunction(){
//...
}
}
Troubleshooting
If a Blazor application throws unexpected exceptions, refer to the following help topic: Troubleshooting.