How to prevent specific row selection in Blazor DataGrid?

Answer:

By rendering the checkbox in HeaderTemplate and performing the selection operation using external methods(GetRowIndexByPrimaryKey, SelectRows, ClearSelection methods of the Grid), specific rows can be disabled and selection can be prevented. Here is the code snippet for reference.

<SfGrid @ref="Grid" DataSource="@Orders" AllowSelection="true" AllowPaging="true">

<GridSelectionSettings Type="SelectionType.Multiple">GridSelectionSettings>

<GridEvents QueryCellInfo="QueryCellInfoHandler" TValue="Order">GridEvents>

<GridColumns>

<GridColumn Type="ColumnType.CheckBox" Width="50">

<HeaderTemplate>

<SfCheckBox TChecked="bool" @onchange="onChange">SfCheckBox> //rendered checkbox in checkbox column

HeaderTemplate>

GridColumn>

<GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" IsPrimaryKey="true" TextAlign="TextAlign.Right" Width="120">GridColumn>

. . .

GridColumns>

SfGrid>

@code{

SfGrid Grid;

List<double> termsList = new List<double>();

public List Orders { get; set; }

. . .

public void QueryCellInfoHandler(QueryCellInfoEventArgs args)

{

if (args.Column.Type == ColumnType.CheckBox && args.Data.CustomerID == "ALFKI")

{

args.Cell.AddClass(new string[] { "e-checkbox-disabled" }); //disabled selection for particular rows

}

}

private async Task onChange(Microsoft.AspNetCore.Components.ChangeEventArgs args)

{

if(args.Value.ToString() == "True")

{

var CurrentView = await Grid.GetCurrentViewRecords(); //get current view records

var IsVisible = CurrentView.Where(or => or.CustomerID != "ALFKI"); // get the other row details other than disabled row

foreach (var item in IsVisible)

{

var rowindex = await Grid.GetRowIndexByPrimaryKey(item.OrderID); //get row index using primary key

termsList.Add(rowindex);

}

await Grid.SelectRows(termsList.ToArray()); //select the rows using SelectRows method

} else

{

await Grid.ClearSelection(); //clear selection

}

}

}

<style>

.e-checkbox-disabled {

background-color: #ddd;

pointer-events: none;

}

style>


Find the sample to prevent specific row selection in Blazor DataGrid here.


Loader.
Up arrow icon