Is it possible to navigate the data grid using up/down arrows?
It is not possible at the moment to navigate with key presses. The closes we have is to use ScrollToPixels
and ScrollToRow
APIs.
To make it work as you desire, you could assign the ElementId
to the DataGrid and then use it with JS to capture the onkeydown
and then call the mentioned API through the JSInterop.
I tried it but it doesn't work. Did you write a piece of code like you mentioned? Is it possible to share it?
Now that I re-read your original message I wonder if I understood you correctly. Do you wish to scroll the table up and down with the keyboard? Or navigate through the editing fields?
I wish to scroll the table up and down with the keyboard up arrow down arrow of page down page up.
Hello,
Here's a very rough unoptimized implementation of what you're requesting:
https://media.giphy.com/media/2P8lemvuZiCeDMcMZc/giphy.gif
@code {
[Inject] EmployeeData EmployeeData { get; set; }
private IEnumerable<Employee> inMemoryData;
[Inject] IJSRuntime JSRuntime { get; set; }
private DataGrid<Employee> _dataGridRef;
public Employee SelectedRow { get; set; }
private DotNetObjectReference<Dashboard>? dotNetObject;
protected override async Task OnInitializedAsync()
{
dotNetObject = DotNetObjectReference.Create(this);
inMemoryData = (await EmployeeData.GetDataAsync().ConfigureAwait(false)).Take(25);
await base.OnInitializedAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("InitializeDataGridKeyDownListener", dotNetObject, _dataGridRef.ElementId);
}
await base.OnAfterRenderAsync(firstRender);
}
[JSInvokable]
public Task OnArrowDown()
{
Console.WriteLine("OnArrowDown");
var idx = _dataGridRef.DisplayData.ToList().IndexOf(SelectedRow);
if (idx < _dataGridRef.DisplayData.Count())
{
return _dataGridRef.Select(_dataGridRef.DisplayData.ElementAt(idx + 1));
}
return Task.CompletedTask;
}
[JSInvokable]
public Task OnArrowUp()
{
Console.WriteLine("OnArrowUp");
var idx = _dataGridRef.DisplayData.ToList().IndexOf(SelectedRow);
if (idx > 0)
{
return _dataGridRef.Select(_dataGridRef.DisplayData.ElementAt(idx - 1));
}
return Task.CompletedTask;
}
}
function InitializeDataGridKeyDownListener(dotNetObject, elementId) {
var dotNetInstance = dotNetObject;
document.getElementById(elementId).querySelectorAll('tr').forEach(x => {
x.setAttribute("tabindex", 0); //Element needs to be focusable
x.addEventListener("keydown", function (e) {
if (e.key == "ArrowUp") {
dotNetInstance.invokeMethodAsync("OnArrowUp");
}
if (e.key == "ArrowDown") {
dotNetInstance.invokeMethodAsync("OnArrowDown");
}
});
});
}
That is a good approach that is close to what I was thinking. it might be a good idea to also have it built-in in Blazorise. @David-Moreira what do you think?
I tried various techniques but I wasn't able to capture the key pressed to use the select or scroll to next row. Is it possible?