How to use radio button instead of checkbox for row selection of grid

16 Aug 20234 minutes to read

Checkbox selection provides an option to select datagrid records with the help of a checkbox in each row. Instead, you can render the radio button for selecting the Grid row. This can be achieved by using the column template feature of the Grid.

In the following sample, the SfRadioButton component is rendered in the Grid column. In the valueChange event of the SfRadioButton, you can select the row using the selectRow method of the Grid based on the row index fetched from the PrimaryKey column value of the Grid. To prevent selection in the Grid by clicking the row, the CheckboxOnly property is enabled.

@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Buttons

<SfGrid @ref="GridInstance" DataSource="@Orders" AllowSelection="true" AllowPaging="true" TValue="Order">
    <GridSelectionSettings CheckboxOnly="true"></GridSelectionSettings>
    <GridColumns>
        <GridColumn>
            <Template>
                @{
                    var PrimaryVal = (context as Order);
                    <SfRadioButton @ref="RadioButtonInstance"  Name="RadioBtn "Value="@PrimaryVal.CustomerID" ValueChange="ValueChange" TChecked="string"></SfRadioButton>
                }
            </Template>
        </GridColumn>
        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name"  IsPrimaryKey="true" >
        </GridColumn>
        <GridColumn Field=@nameof(Order.ShipCity) HeaderText="Ship City" Width="110"></GridColumn>
        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2"></GridColumn>
        <GridColumn Field=@nameof(Order.OrderDate) HeaderText="Order Date" Format="d" Width="110" Type="ColumnType.Date"></GridColumn>
    </GridColumns>
</SfGrid>

@code {
    public List<Order> Orders { get; set; }
    SfRadioButton<string> RadioButtonInstance;
    SfGrid<Order> GridInstance;

    protected override void OnInitialized()
    {
        Orders = Enumerable.Range(1, 4).Select(x => new Order()
        {
            CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[x],
             ShipCity = (new string[] { "Berlin", "Madrid", "Cholchester", "Marseille", "Tsawassen" })[new Random().Next(5)],
              Freight = 2.1 * x,
               OrderDate = DateTime.Now.AddDays(-x),
        }).ToList();
    }
    public async void ValueChange(ChangeArgs<string> args)
    {
        var index = await GridInstance.GetRowIndexByPrimaryKey(args.Value); // Fetch the row index based on the unique value of RadioButton.
        GridInstance.SelectRow(index); // Select the corresponding Grid row.
    }
    public class Order {
        public int? OrderID { get; set; }
        public string CustomerID { get; set; }
        public DateTime? OrderDate { get; set; }
        public double? Freight { get; set; }
        public string ShipCity { get; set; }
    }
}