Back to Devexpress

DxComboBoxSettings Class

blazor-devexpress-dot-blazor-1ef9de57.md

latest15.8 KB
Original Source

DxComboBoxSettings Class

Contains settings of an auto-generated combo box editor.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
public class DxComboBoxSettings :
    DxDropDownEditSettings,
    IComboBoxSettings,
    IDropDownEditSettings,
    IButtonEditSettings,
    ITextEditSettings,
    IEditSettings

Remarks

Grid and TreeList components automatically generate editors for columns based on associated data types. For the enum type, they generate a combo box editor.

You can replace the default editor of any column with a combo box. Refer to the following section for additional information: Change a Column Editor to Combo Box.

Auto-Generated Combo Box in Filter Row and Edit Cells

Grid and TreeList components automatically display column editors in the filter row and in data rows during edit operations. In the following code snippet, the Grid displays a combo box editor for the Summary column (enumerator data type):

razor
@inject IDbContextFactory<NorthwindContext> NorthwindContextFactory

<DxGrid Data="@forecasts"
        ShowFilterRow="true"
        EditMode="GridEditMode.EditRow"
        CssClass="my-class">
    <Columns>
        <DxGridCommandColumn />
        <DxGridDataColumn FieldName="Date" />
        <DxGridDataColumn FieldName="Summary" />
        <DxGridDataColumn Caption="Temperature" FieldName="TemperatureC" />
    </Columns>
</DxGrid>

@code {
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync() {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}
csharp
public class WeatherForecastService {

    public enum Summaries {
        Freezing, Bracing, Chilly, Cool, Mild, Warm, Balmy, Hot, Sweltering, Scorching};

    public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) {
        var rng = new Random();
        return Task.FromResult(Enumerable.Range(1, 100).Select(index => new WeatherForecast {
            Date = startDate.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = (Summaries)rng.Next(Enum.GetNames(typeof(Summaries)).Length)
        }).ToArray());
    }
}
csharp
public class WeatherForecast {
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public Summaries Summary { get; set; }
}

Auto-Generated Combo Box in Edit Forms

The inline or pop-up edit form can also display auto-generated editors. To place an editor in a form, add the GetEditor method to the EditFormTemplate.

In the following code snippet, the Grid displays an auto-generated combo box editor for the Summary column:

razor
@inject IDbContextFactory<NorthwindContext> NorthwindContextFactory

<DxGrid Data="@forecasts"
    PageSize="7">
    <Columns>
        <DxGridCommandColumn />
        <DxGridDataColumn FieldName="Date" />
        <DxGridDataColumn FieldName="Summary" />
        <DxGridDataColumn Caption="Temperature" FieldName="TemperatureC" />
    </Columns>
    <EditFormTemplate Context="editFormContext">
        <DxFormLayout>
            <DxFormLayoutItem Caption="Date:">
                @editFormContext.GetEditor("Date")
            </DxFormLayoutItem>
            <DxFormLayoutItem Caption="Temperature:">
                @editFormContext.GetEditor("TemperatureC")
            </DxFormLayoutItem>
            <DxFormLayoutItem Caption="Summary:" >
                @editFormContext.GetEditor("Summary")
            </DxFormLayoutItem>
        </DxFormLayout>
    </EditFormTemplate>
</DxGrid>

@code {
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync() {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Display Text in Filter Menu

You can use the DxComboBoxSettings object to format filter list items.

The following code snippet uses the DxComboBoxSettings object to specify the text used to display the Category column’s filter menu items:

razor
<DxGrid Data="GridData"
    FilterMenuButtonDisplayMode="GridFilterMenuButtonDisplayMode.Always"
    @* ... *@
    VirtualScrollingEnabled="true">
    <Columns>
        <DxGridDataColumn FieldName="OrderDate" Width="140px" />
        <DxGridDataColumn FieldName="ProductName" MinWidth="100" />
        <DxGridDataColumn FieldName="CategoryId" Caption="Category" Width="130px">
            <EditSettings>
                <DxComboBoxSettings Data="Categories" ValueFieldName="CategoryId" TextFieldName="CategoryName" />
            </EditSettings>
        </DxGridDataColumn>
        <DxGridDataColumn FieldName="UnitPrice" DisplayFormat="c2" Width="140px" />
        <DxGridDataColumn FieldName="Quantity" Width="110px" />
        <DxGridDataColumn FieldName="Discount" DisplayFormat="p0" Width="110px" />
        <DxGridDataColumn FieldName="Total"
                          UnboundType="GridUnboundColumnType.Decimal"
                          UnboundExpression="[UnitPrice] * [Quantity] * (1 - [Discount])"
                          DisplayFormat="c2"
                          Width="110px">
            <FilterMenuTemplate>
                <Grid_Filtering_ColumnFilterMenu_CustomRange FilterContext="context" Items="TotalPriceIntervals" />
            </FilterMenuTemplate>
        </DxGridDataColumn>
        <DxGridDataColumn FieldName="Shipped"
                          UnboundType="GridUnboundColumnType.Boolean"
                          UnboundExpression="[ShippedDate] <> Null"
                          Width="100px" />
    </Columns>
</DxGrid>

Change a Column Editor to Combo Box

Follow the steps below to replace a column’s default editor with a combo box:

  1. Add DxComboBoxSettings in the column’s EditSettings property.
  2. Specify the Data combo box setting to bind the editor to a data source.
  3. If the data source contains complex data, specify ValueFieldName and TextFieldName settings to supply combo box items with values and corresponding display text strings.

The following code snippet replaces default editors of Category and Unit Price columns with combo boxes:

razor
@inject IDbContextFactory<NorthwindContext> NorthwindContextFactory

<DxGrid Data="Products"
        EditMode="GridEditMode.EditRow">
    <Columns>
        <DxGridCommandColumn />
        <DxGridDataColumn FieldName="CategoryId" Caption="Category">
            <EditSettings>
                <DxComboBoxSettings Data="Categories"
                                    ValueFieldName="CategoryId"
                                    TextFieldName="CategoryName"/>
            </EditSettings>
        </DxGridDataColumn>
        <DxGridDataColumn FieldName="ProductName" />
        <DxGridDataColumn FieldName="UnitPrice">
            <EditSettings>
                <DxComboBoxSettings Data="Prices" DisplayFormat="C" EditFormat="F" />
            </EditSettings>
        </DxGridDataColumn>
        <DxGridDataColumn FieldName="UnitsInStock" />
        <DxGridDataColumn FieldName="QuantityPerUnit" />
    </Columns>
</DxGrid>
@code {
    NorthwindContext Northwind { get; set; }
    List<Product> Products { get; set; }
    List<Category> Categories { get; set; }
    List<decimal?> Prices = new List<decimal?>() { 5, 10, 25, 50, 100};

    protected override async Task OnInitializedAsync() {
        Northwind = NorthwindContextFactory.CreateDbContext();
        Products = await Northwind.Products.ToListAsync();
        Categories = await Northwind.Categories.ToListAsync();
    }

    public void Dispose() {
        Northwind?.Dispose();
    }
}
csharp
using Microsoft.EntityFrameworkCore;
#nullable disable

namespace Grid.Northwind {
    public partial class NorthwindContext : DbContext {

        public NorthwindContext(DbContextOptions<NorthwindContext> options)
            : base(options) {
        }
        // ...
        public virtual DbSet<Category> Categories { get; set; }
        public virtual DbSet<Product> Products { get; set; }
        // ...
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            if(!optionsBuilder.IsConfigured) {
                optionsBuilder.UseSqlServer("Server=.\\sqlexpress;Database=Northwind;Integrated Security=true");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
            // ...
            modelBuilder.Entity<Category>(entity => {
                entity.HasIndex(e => e.CategoryName, "CategoryName");
                entity.Property(e => e.CategoryId).HasColumnName("CategoryID");
                entity.Property(e => e.CategoryName)
                    .IsRequired()
                    .HasMaxLength(15);
                entity.Property(e => e.Description).HasColumnType("ntext");
                entity.Property(e => e.Picture).HasColumnType("image");
            });
            modelBuilder.Entity<Product>(entity => {
                entity.HasIndex(e => e.CategoryId, "CategoriesProducts");
                entity.HasIndex(e => e.CategoryId, "CategoryID");
                entity.HasIndex(e => e.ProductName, "ProductName");
                entity.HasIndex(e => e.SupplierId, "SupplierID");
                entity.HasIndex(e => e.SupplierId, "SuppliersProducts");
                entity.Property(e => e.ProductId).HasColumnName("ProductID");
                entity.Property(e => e.CategoryId).HasColumnName("CategoryID");
                entity.Property(e => e.ProductName)
                    .IsRequired()
                    .HasMaxLength(40);
                entity.Property(e => e.QuantityPerUnit).HasMaxLength(20);
                entity.Property(e => e.ReorderLevel).HasDefaultValueSql("((0))");
                entity.Property(e => e.SupplierId).HasColumnName("SupplierID");
                entity.Property(e => e.UnitPrice)
                    .HasColumnType("money")
                    .HasDefaultValueSql("((0))");
                entity.Property(e => e.UnitsInStock).HasDefaultValueSql("((0))");
                entity.Property(e => e.UnitsOnOrder).HasDefaultValueSql("((0))");
                entity.HasOne(d => d.Category)
                    .WithMany(p => p.Products)
                    .HasForeignKey(d => d.CategoryId)
                    .HasConstraintName("FK_Products_Categories");
            });
            // ...
            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}
csharp
public partial class Product {
    public Product() {
        OrderDetails = new HashSet<OrderDetail>();
    }

    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public int? SupplierId { get; set; }
    public int? CategoryId { get; set; }
    public string QuantityPerUnit { get; set; }
    public decimal? UnitPrice { get; set; }
    public short? UnitsInStock { get; set; }
    public short? UnitsOnOrder { get; set; }
    public short? ReorderLevel { get; set; }
    public bool Discontinued { get; set; }

    public virtual Category Category { get; set; }
}
csharp
public partial class Category {
    public Category() {
        Products = new HashSet<Product>();
    }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public byte[] Picture { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

View Example: Create a Foreign Key (ComboBox) Column

Runtime Customization

At runtime, call the GetColumnEditSettings method to access settings of a combo box editor in the specified column. The following code snippet dynamically disables the editor.

razor
<DxGrid @ref="Grid"
        Data="Products"
        EditMode="GridEditMode.EditRow">
    <Columns>
        <DxGridCommandColumn />
        <DxGridDataColumn FieldName="CategoryId" Caption="Category">
            <EditSettings>
                <DxComboBoxSettings Data="Categories"
                                    ValueFieldName="CategoryId"
                                    TextFieldName="CategoryName"/>
            </EditSettings>
        </DxGridDataColumn>
        <DxGridDataColumn FieldName="ProductName" />
        <DxGridDataColumn FieldName="UnitPrice" />
        <DxGridDataColumn FieldName="UnitsInStock" />
        <DxGridDataColumn FieldName="QuantityPerUnit" />
    </Columns>
</DxGrid>
<DxButton Text="Disable the Category" Click="Button_Click" />

@code {
    IGrid Grid { get; set; }
    NorthwindContext Northwind { get; set; }
    List<Product> Products { get; set; }
    List<Category> Categories { get; set; }

    void Button_Click() {
        var comboBoxSettings = Grid.GetColumnEditSettings<IComboBoxSettings>("CategoryId");
        if(comboBoxSettings != null){
            Grid.BeginUpdate();
            comboBoxSettings.Enabled = false;
            Grid.EndUpdate();
        }
    }

    protected override async Task OnInitializedAsync() {
        Northwind = NorthwindContextFactory.CreateDbContext();
        Products = await Northwind.Products.ToListAsync();
        Categories = await Northwind.Categories.ToListAsync();
    }

    public void Dispose() {
        Northwind?.Dispose();
    }
}

Implements

IComponent

IHandleEvent

IHandleAfterRender

IDisposable

IComboBoxSettings

IDropDownEditSettings

IButtonEditSettings

ITextEditSettings

IEditSettings

Inheritance

Object ComponentBase DevExpress.Blazor.Internal.BranchedRenderComponent DevExpress.Blazor.Internal.ParameterTrackerSettingsComponent DxEditSettings DxTextEditSettings DxButtonEditSettings DxDropDownEditSettings DxComboBoxSettings

See Also

DxComboBoxSettings Members

DevExpress.Blazor Namespace