Declined
Last Updated: 23 Nov 2023 11:28 by ADMIN
ben
Created on: 28 Apr 2020 17:52
Category: Grid
Type: Feature Request
1
Grid Row Template with Selection - Unsure how to Bind to Selected Item

Looking through the examples I can't find one with SelectionMode="GridSelectionMode.Multiple" and using a RowTemplate.

ADMIN EDIT: This is not a bug in the component, an example of how this can be implemented by the app is available in the comments.

I'm not sure what I should be binding my checkbox to so it accurately reflects selection state.

From the RowTemplate Example adding SelectionMode:

<TelerikGrid Data=@GridData

@bind-SelectedItems="@SelectedItems"

SelectionMode="GridSelectionMode.Multiple" Height="@Height">

<RowTemplate Context="product">  @*Trying to inspect what is generated in the examples I came up with this, but not sure what to bind to checked*@

<td role="gridcell" colspan=0 data-col-index="0">
                    <span>
                        <input class="k-checkbox k-grid-checkbox telerik-blazor" type="checkbox" />
                    </span>
                </td>

<td> <img class="rounded-circle" src="@($"images/{product.ProductId}.jpg")" alt="Alternate Text" /> @product.ProductName </td> <td> @(String.Format("{0:C2}", product.UnitPrice)) </td> </RowTemplate> <GridColumns> <GridColumn Field=@nameof(Product.ProductName) Title="Product Name" /> <GridColumn Field=@nameof(Product.UnitPrice) Title="Unit Price" /> </GridColumns> </TelerikGrid>

12 comments
ADMIN
Nadezhda Tacheva
Posted on: 23 Nov 2023 11:28

Hi Michal,

Please keep in mind that the statement in my last post targets the built-in selection. It is generally possible to use the standard built-in selection with RowTemplate (excluding the Checkbox selection). However, if you want to override that, so the user does not have to use either Ctrl or Shift to select multiple items, you should take full control of how the selection occurs. Similar to the approach listed here: https://docs.telerik.com/blazor-ui/knowledge-base/grid-select-or-deselect-item-on-row-click

A crucial part to ensure the custom selection will be working is to handle the SelectedItemsChanged event and do not execute any logic in it. Otherwise, the built-in selection may interfere with your custom logic in the OnRowClick handler. It is possible that you are hitting this in your app. 

I am not aware of your exact current configuration but I have prepared a runnable sample that shows custom selection on row click in a Grid that uses RowTemplate: https://blazorrepl.telerik.com/GxlvGHPb23TJTPGf23.

I hope that will help you achieve the desired result on your end.

Regards,
Nadezhda Tacheva
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources!
Michal
Posted on: 20 Nov 2023 17:07

Hi Nadezhda,

 after some time of trying to do it another way, for me it seems like something important is missig(in any sample, including those down here), or there is a bug:

" the user must use either Ctrl or Shift to select multiple items"

- take a look at my working sample where keyboard interaction is NOT REQUIRED(digged as recommended suggetsions from another discusion thread) and also without specifically clicking on the checkboxes.

Click on the row equals selects the row. = thats the goal.

Everything is working fine, with MultipleSelection enabled and WITHOUT row template.
- yes, its already handled by own logic and code
- now, HOW to apply the same with "row template" scenario? No Checkbox(or if its need some invisible dummy one, HOW/where/why?), no keyboard.

Some interlal logic of the grid EATING selected rows AFTER custom code(OnGridRowClicked). How to avoid it? This seems as the core of the problem, but also, its out of the scope how to handle it wihtout going into reflection of the grid logic(which you don't want to do at best).

- what i understand(and is acceptable): that in row template scenario, selected rows maybe not rendered "by the grid itself" as selected, and needs to be done by myself.
- BUT what is NOGO: grid cannot EAT the binded selcted values at OnGridRowClicked .Of coures, the same apply when you PRESELECTing values.

Ill be glad for any kind of workign suggestion or fix in near release.

ADMIN
Nadezhda Tacheva
Posted on: 06 Nov 2023 13:45

Hi Michal,

If the Checkbox selection is not enabled, the user must use either Ctrl or Shift to select multiple items. Please see Multiple row selection basics for more clarity.

For multiple selection on mobile devices (you've mentioned you are using a tablet), the only way to allow the user to select multiple rows is to enable Checkbox selection.

In case one is using a Row Template, the Checkbox selection cannot work out of the box as discussed earlier in this thread. Therefore, the selection should be handled by the developer. Still, you will need to render a cell with a custom Checkbox if you want to let the user select multiple rows on mobile devices. Please refer to the example that my colleague Marin sent on 30 Apr 2020 4:10 PM.

Regards,
Nadezhda Tacheva
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources!
Michal
Posted on: 01 Nov 2023 12:54

Hello Nadezhda,

 you made great job summarizing lot of the ways, BUT, make a little step back:

- Do not think about keyboard navigation, there is no mention about the keyboard. Just clicking the rows - on the tablet, by finger, mouse thats all.
- Click on the row = even at all your examples, its not possible to SELECT MULTIPLE rows by just clicking. You always get only SINGLE row. 
Take a look at the video = just clicking the rows, thats all - no keyboard is involved.

"

  • Do not handle OnRowClick to alter the selection. Let the Grid handle that for you.

"

Its nice idea, but without this, even the second(bottom grid in example )doesnt work. So it has its place. Same apply to the invisible checboxes. You may call it "hack" but its the only way how to:
- make the multiple rows selection get working, without visible checkbox, just by clicking the N-rows.
- unfortunately, the same "hack" doesnt work with row template.

back to the root:
1) - take my example, run it in VS, and TRY to select 3 rows by clicking them, row by row, at the BOTTOM grid. = OK
2) - take my example, run it in VS, TOP grid, and TRY to select 3 rows by clicking them, row by row, at the BOTTOM grid. = do you see the problem as at the video? It behaves differently(like single row selection mode), but it should act same(like multiple rows selection mode).

Thanks, iam opened the ticket/bug report with link to this discusion. Hope we have now same mindset(just clicking the rows :) )

ADMIN
Nadezhda Tacheva
Posted on: 01 Nov 2023 09:59

Hi Michal,

Thank you for confirming that no Checkbox selection is needed! In this case, you can use the built-in multiple selection and two-way binding for the selected items. Let me provide details on both the discussed examples.

Multiple Selection specifics

When multiple selection is enabled and Checkbox selection is not enabled, the user can select multiple items by:

  • Ctrl + Click (or Ctrl + Space when the Grid is navigable) - thus the user will select one item per click. This combination selects or deselects the current row, while persisting previously selected rows.

  • Shift + Click (or Shift + Space when the Grid is navigable) - thus the user will select a range of items. This combination selects all the rows between the last selected one (with Space or mouse click) and the one holding the focused cell (or currently clicked cell).

Example I shared

In the example I shared, I am observing proper multiple selection when I am using the above-listed commands.

See attached a video of the result I am getting: grid-multiple-selection.

Example you shared

In the code you initially provided, I see you are handling the OnRowClick event to modify the SelectedItems collection. This effectively interferes with the built-in selection mechanism.

In addition, you have also included the CheckBox column and enabled CheckBoxOnlySelection as follows:

<GridCheckboxColumn CheckBoxOnlySelection="true" Visible="false" @key="@("sIDX1")" SelectAll="false" />

This is not needed if you do not want to implement Checkbox selection as you have informed me.

Here are the changes I suggest:

  • Do not handle OnRowClick to alter the selection. Let the Grid handle that for you.
  • Remove the GridCheckboxColumn declaration as you will not be using it.

I've modified your code and the selection behaves as expected on my end. Again, I am selecting items when holding Shift or Ctrl as per the Grid specification. I'm attaching the updated code, so you can test it on your end.

Take your time to revise that and please let me know if you are facing any other issues. If so, please open a dedicated ticket on the matter, so it can be addressed in the standard 24h support time. The feedback portal items generally have longer response time.

Regards,
Nadezhda Tacheva
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources!
Michal
Posted on: 25 Oct 2023 12:46

Hi Nadezda,

 thanks for quick response, but even your sample/repl doesnt working as expected also. Its selecting only SINGLE selection and the problem is that it should be MULTIPLE :)

Expando object was purpose, to eliminate identifying troubles between simple/comples objects.

- in my sample "dummy" invisible checkbox was just hack - if you remove them, it acts as signle selection mode = wrong.

- but that hack doesnt work with row template(with or without GridCheckboxColumn), same as your example = also wrong

So to confirm: yes, i do not wont to use checkbox selection at all. Also no need to be visible, no need to be present as column,anywhere. BUT, binding multiple selection must work in all cases and presented as higlighted rows.

Hope the video and description helped = bottom grid "is partly ok"(requires that dummy invisible checbkoxcolumn), but the top one is stubborn in all cases. Is it time for the ticket, or am i missed something?

Michal
Posted on: 25 Oct 2023 12:01

Hi Marin,

 please take a closer look at the example.

"You can use the HeaderTemplate to add a checkbox and implement the desired logic there too."

There is NO NEED for chechboxes at all(they are also hiden in sample), just binding selected itemS(multiple) by clicking at rows.

If you use ROW TEMPLATE, binding selected items stops working at all. Is there some hidden option, or required markup to get it working as at second sample? Or is it a bug?

Attached Files:
ADMIN
Nadezhda Tacheva
Posted on: 25 Oct 2023 11:50

Hi Michal,

When RowTemplate is used, you can still use two-way binding of the SelectedItems. The issue arises if one wants to use CheckBox selection. For this functionality, the Grid needs to render a CheckboxColumn which cannot happen if RowTemplate is used. In this case, the Grid no longer controls its own rendering, so the CheckBox selection has to be implemented by the app.

You've mentioned that you do not want any CheckBox but the example you've shared includes a CheckboxColumn. It may be a leftover, though, can you please confirm?

Other than that, you can use the standard selection: https://blazorrepl.telerik.com/GnbYcJFF34uUjfM721.

I've tested your sample but I do not see an issue, I am able to select all items in both Grids. Please let me know if I am missing something. You may open a dedicated ticket where we can discuss the specific use case.

Side note: The code snippet you provided uses ExpandoObject. We've registered a problem with that in REPL - there are no errors as you are saying but the code does not compile. We have logged it for fixing in a future version of the tool.

Regards,
Nadezhda Tacheva
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources!
Michal
Posted on: 19 Oct 2023 06:38

Hello Marin,

 to be sure, scenario when using Grid-RowTemplate, BINDING to selectedItems with multiple selection doesnt work at all?

I do not wont any check box, just click on row and make it "selected". But it somehow lose the selected items.

- First gir is the problematic one
- Second grid is "standard" ok- bind

Try to select all rows on first grid(top one) versus on second(bottom)

Thanks for the tips, whats missing.

The goal scenario is to switch grid runtime to "mobile" view vs full desktop view with same data logic.(only one of the grid is visible at once).  So take it as extremly simplified, but reproducible sample.

sample fo REPL doesnt print any error, but not starting for me, here is complete testing setup(fully working in VS):

@using System.Collections.Generic;
@using System.Dynamic;
    <span>Selection bind not working as expected:</span>
    <TelerikGrid TItem="ExpandoObject"
    @bind-SelectedItems="@gSelectedItems"
                 OnRowClick="@OnGridRowClicked"
                 SelectionMode="GridSelectionMode.Multiple"
                 OnRead=@gHLReadItems
                 RowHeight="60">
        <RowTemplate Context="ctx">
            <td>
                @{
                    var it = (ctx as IDictionary<stringobject>);
                    @(it["Name"].ToString())
                }
            </td>
        </RowTemplate>
        <GridColumns>
            <GridCheckboxColumn CheckBoxOnlySelection="true" Visible="false" @key="@("sIDX1")" SelectAll="false" />
            <GridColumn Field="Name" FieldType=@typeof(stringTitle="Name" />
        </GridColumns>
    </TelerikGrid>
<span>WORKs OK:</span>
    <TelerikGrid TItem="ExpandoObject"
    @bind-SelectedItems="@gSelectedItems"
                 OnRowClick="@OnGridRowClicked"
                 SelectionMode="GridSelectionMode.Multiple"
                 OnRead=@gHLReadItems
                 RowHeight="60">
        <GridColumns>
            <GridCheckboxColumn CheckBoxOnlySelection="true" Visible="false" @key="@("sIDX2")" SelectAll="false" />
            <GridColumn Field="Name" FieldType=@typeof(stringTitle="Name" />
        </GridColumns>
    </TelerikGrid>
        
@code
{
    private List<ExpandoObject> RowData;
    IEnumerable<ExpandoObject> gSelectedItems { get; set; } = Enumerable.Empty<ExpandoObject>();
    protected override void OnInitialized()
    {
        
        RowData = new List<ExpandoObject>();
        dynamic obj0 = new ExpandoObject();
        obj0.Name = "Tester";
        RowData.Add(obj0);
        dynamic obj1 = new ExpandoObject();
        obj1.Name = "Testovicz";
        RowData.Add(obj1);
        dynamic obj2 = new ExpandoObject();
        obj2.Name = "Selectant";
        RowData.Add(obj2);
    }
    protected async Task gHLReadItems(GridReadEventArgs args)
    {
        //RowData are readen from DYNAMIC source, cannot add any NEW property to it
        args.Data = RowData;
        args.Total = 3;
    }
    protected void OnGridRowClicked(GridRowClickEventArgs args)
    {
        var it = args.Item as ExpandoObject;
        if (gSelectedItems.Any(x => x == it))
        {
            gSelectedItems = gSelectedItems.Where(x => x != it);
        }
        else
        {
            gSelectedItems = gSelectedItems.Union(RowData.Where(x => x == it));
        }
    }
}
ADMIN
Marin Bratanov
Posted on: 01 May 2020 07:33

Hello Ben,

You can use the HeaderTemplate to add a checkbox and implement the desired logic there too.

 

Regards,
Marin Bratanov
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
ben
Posted on: 30 Apr 2020 14:38

Marin,

What is the recommended guidance for the column header if one desires to click and 'select all'?  The current example provides a static column.

 

 

ADMIN
Marin Bratanov
Posted on: 30 Apr 2020 13:10

Hello Ben,

When the RowTemplate is used, you take over management of the model and this includes the selection. Perhaps the easiest way is to add a boolean field to the grid model to indicate selection so you can use it for the state of the checkbox.

<TelerikGrid Data=@GridData Pageable="true"
             SelectedItems="@SelectedItems"
             SelectionMode="GridSelectionMode.Multiple">
    <RowTemplate Context="employee">
        <td>
            <TelerikCheckBox Value="@employee.IsSelected" ValueChanged="@((bool value) => ChangeHandler(value, employee.EmployeeId))" />
        </td>
        <td>
            <img class="rounded-circle" src="@($"images/{employee.EmployeeId}.jpg")" alt="Alternate Text" />
            @employee.Name
        </td>
        <td>
            @employee.Team
        </td>
    </RowTemplate>
    <GridColumns>
        <GridColumn Title="Select" />
        <GridColumn Field=@nameof(Employee.Name) />
        <GridColumn Field=@nameof(Employee.Team) Title="Team" />
    </GridColumns>
</TelerikGrid>

@if (SelectedItems != null)
{
    <ul>
        @foreach (Employee employee in SelectedItems)
        {
            <li>
                @employee.Name
            </li>
        }
    </ul>
}

@code{
    public List<Employee> GridData { get; set; }
    public IEnumerable<Employee> SelectedItems { get; set; } = Enumerable.Empty<Employee>();

    protected override void OnInitialized()
    {
        GridData = new List<Employee>();
        for (int i = 0; i < 15; i++)
        {
            GridData.Add(new Employee()
            {
                EmployeeId = i,
                Name = "Employee " + i.ToString(),
                Team = "Team " + i % 3
            });
        }

        // select Employee with 3 through 5. Not required
        SelectedItems = GridData.Skip(2).Take(3).ToList();
        foreach (var item in SelectedItems)
        {
            item.IsSelected = true;
        }
    }

    void ChangeHandler(bool isSelected, int employeeId)
    {
        Employee currEmployee = GridData.Where(empl => empl.EmployeeId == employeeId).First();
        if (currEmployee != null)
        {
            //update the model first
            currEmployee.IsSelected = isSelected;
            
            //handle selected items collection
            var itemsToSelect = SelectedItems.ToList();
            if (isSelected)
            {
                itemsToSelect.Add(currEmployee);
            }
            else
            {
                itemsToSelect.Remove(currEmployee);
            }
            SelectedItems = new List<Employee>(itemsToSelect);
        }
    }

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Team { get; set; }
        // for row selection with a row template
        public bool IsSelected { get; set; }
    }
}

 

Regards,
Marin Bratanov
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.