"Enter" keydown event is not functioning on toolbar button after navigating from a cell in a Syncfusion Grid.

Hi team.


I have a navigation system in which pressing "Enter" in a cell column focuses on the Add toolbar button, allowing the addition of another item via the "Enter" key as well. The problem is that "Enter" seems not to function after adding two items.


Image_9591_1730805226823


I noticed that the edit wrap still remains on the cell after I press 'Enter.' It seems the 'Enter' key is still active in the cell even though the focus has already been set on the Add toolbar button."

 Image_2204_1730805410549


//Here is my code in razor for freegoods column..

   @*FreeGoods*@

 <GridColumn Field=@nameof(DRdetailEdit.FreeGoods) HeaderText="FreeGoods"

             EditType="EditType.DefaultEdit"

             Width="120"

             AllowEditing="true"

            CustomAttributes="@(new Dictionary<string, object>(){ { "class", "e-attr" }})">

          <EditTemplate Context="EditContext">

          <div @onkeydown="@(e => KeyDownHandlerFreeGoods(e))">


 <SfDropDownList ID="FreeGoods"

             @bind-Value="@((EditContext as DeliveryReceiptsDetailEdit).FreeGoods)"

             DataSource="@FreeGoodies"

             TItem="FreeGoods"

             TValue="string"

             Placeholder="FreeGoods"

             PopupHeight="150px"

             PopupWidth="300px"

             AllowFiltering="true">

     <DropDownListFieldSettings Value="Select" Text="Select"></DropDownListFieldSettings>

 </SfDropDownList>

         </div>

     </EditTemplate>

     <HeaderTemplate Context="HeaderContext">

         <div>

             <span class="oi oi-command e-icons headericon"></span> FreeGoods

         </div>

     </HeaderTemplate>

// Base code for focusing on the Add button when 'Enter' is pressed.

public async Task KeyDownHandlerFreeGoods(KeyboardEventArgs args)

{

    var CurrentView = await GridDetail.GetCurrentViewRecordsAsync();

    if (GridDetail.IsEdit && args.Key == "Enter" && RowIndexDetail == CurrentView.Count - 1)

    {

        await Task.Delay(200);

        await JSRuntime.InvokeVoidAsync("focus"); // called interop function for focus

    }

}


//JS for focus on add button.

        function focus() {

            document.getElementsByClassName('e-toolbar-item')[0].getElementsByTagName('button')[0].focus();

        }


please refer to my other post which is related to this topic.

https://www.syncfusion.com/forums/180194/focus-in-toolbar  


Hoping you can help me regarding this issue


Thanks and best regards,


Tyrone


15 Replies

NP Naveen Palanivel Syncfusion Team November 6, 2024 11:17 AM UTC

Hi Tyrone,

We have reviewed your query, and it appears that after pressing Enter in the cell, JavaScript is used to move the focus to the Add button in the toolbar. However, after adding two items, the focus no longer moves to the Add button as expected. We created a simple sample and tested it on our end, but we were unable to reproduce the issue. Please refer to the attached sample for reference.

If the reported issue still reproduced, then kindly share the below details to validate further at our end.


  1. Share us the full Grid code snippet and model class.
  2. Could you let us know which type of edit mode you are using (Normal or Batch Edit)?
  3. In the provided code, the variable RowIndexDetail is used. Could you explain what value is being assigned to it and how the assignment is being handled?
  4. Share us the video demonstration of the issue with elaborately, it will be more useful to us.
  5. If possible, share us an simple issue reproduceable sample or try to modify the above mentioned sample.


The above-requested details will be very helpful for us to validate the reported query at our end and provide the solution as early as possible.


Regards,

Naveen Palanivel


Attachment: BlazorApp_Focus_a8abddf6.zip


TY Tyrone November 16, 2024 05:51 AM UTC

Hi Naveen,

My apology for late reply. Something came up lately.

it appears that after pressing Enter in the cell, JavaScript is used to move the focus to the Add button in the toolbar. However, after adding two items, the focus no longer moves to the Add button as expected. 

In correction, Move the focus to the Add button works just fine. The problem is that Enter keypress is not working in "Add button" (to add new row) after it got it's focus.

I just notice that freegoods column is still in editable state even the focus is already in the "Add Button". It might be the cause.

Image_6445_1731735493404

  1. Share us the full Grid code snippet and model class.  
  2. I think your sample attachment is enough to see the problem.. 
    Just change Normal mode to Batch mode. Normal mode works fine but not in Batch. 
  3. Could you let us know which type of edit mode you are using (Normal or Batch Edit)? Batch
  4. In the provided code, the variable RowIndexDetail is used. Could you explain what value is being assigned to it and how the assignment is being handled? It is just the active row derived from Row Select Event. Image_8109_1731735039401
  5. Share us the video demonstration of the issue with elaborately, it will be more useful to us. Please See link for the video,. please refer tp this link.  "Enter key" is irresponsive in "Add Button" at the end of the video.
  6. If possible, share us an simple issue reproduceable sample or try to modify the above mentioned sample. I think your sample attachment is enough to see the problem.. Just change Normal mode to Batch mode.


Hoping for your furthermore reply,


Thank You and Best Regards,


Tyrone





PS Prathap Senthil Syncfusion Team November 21, 2024 04:04 AM UTC

Based on the reported problem, we recommend calling the endEditAsync method when pressing the Enter button and disabling the showConfirmationDialog in the edit settings to achieve the desired functionality. Kindly refer to the code snippet and sample provided below for your reference

  <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" NewRowPosition="NewRowPosition.Bottom" Mode="EditMode.Batch" ShowConfirmDialog="false">

  </GridEditSettings
  public async Task KeyDownHandlerFreeGoods(KeyboardEventArgs args)

    {

        if (args.Key == "Enter" && GridDetail.IsEdit)

        {

            await Task.Delay(200);

           await GridDetail.EndEditAsync();

            await JSInterop.InvokeVoidAsync("focus");

        

        }

    }

 


Reference:
Class SfGrid<TValue> - Blazor API Reference | Syncfusion
Class GridEditSettings - Blazor API Reference | Syncfusion


Attachment: BlazorApp1_a6e06d3a.zip


TY Tyrone November 28, 2024 10:03 AM UTC

Hi  Prathap,


I couldn't apply the  "Await Griddetail.EndEditAsync();" upon "Enter" key in freegoods.. Because I'm using the event to save the lineitems in batch. And I need the green background as indicator for the newly o updated lineitem,

Image_9015_1732787550182

Is there is any workaround?


Thanks and Best Regards,


Tyrone





MS Monisha Saravanan Syncfusion Team November 29, 2024 11:14 AM UTC


Hi Tyrone,


We have prepared a simple sample as per your shared requirement by using ApplyBtachChanges method. Kindly check the below attached sample and code snippet for your reference.


Here in the below highlighted code we have used CloseEditAsync method to close the existing AddForm and by using ApplyBatchChanges we have inserted the added record list. So that the changes will be remain unsaved ( with green background).


Reference: https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.SfGrid-1.html#Syncfusion_Blazor_Grids_SfGrid_1_ApplyBatchChangesAsync_Syncfusion_Blazor_Grids_BatchChanges__0__



<SfGrid @ref="GridDetail" ID="GridDetail" DataSource="@Orders" AllowPaging="true" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" Height="315">

    <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" NewRowPosition="NewRowPosition.Bottom" Mode="EditMode.Batch" ShowConfirmDialog="false">

    </GridEditSettings>

    <GridEvents DataBound="DataBoundHandler" OnBatchSave="BatchSave" TValue="Order"></GridEvents>

    <GridColumns>

        <GridColumn Field=@nameof(Order.FreeGoods) HeaderText="Free Goods" EditType="EditType.DefaultEdit" Width="120" AllowEditing="true">

            <EditTemplate Context="EditContext">

                <div >

                    <SfDropDownList ID="FreeGoods"

                    @bind-Value="@((EditContext as Order).FreeGoods)"

                    @onkeydown="@(e => KeyDownHandlerFreeGoods(e,EditContext as Order ))"

                    DataSource="@FreeGoodies"

                    TItem="string"

                    TValue="string"

                    Placeholder="Free Goods"

                    PopupHeight="150px"

                    PopupWidth="300px"

                    AllowFiltering="true">

                        <DropDownListFieldSettings Value="Select" Text="Select"></DropDownListFieldSettings>

                    </SfDropDownList>

                </div>

            </EditTemplate>

        </GridColumn>

    </GridColumns>

</SfGrid>

 

@code {

    public async Task BatchSave()

    {

        batchdata = new List<Order>();

    }

    public async Task KeyDownHandlerFreeGoods(KeyboardEventArgs args, Order data)

    {

        if (args.Key == "Enter" && GridDetail.IsEdit)

        {

            await Task.Delay(200);

            var val = data.FreeGoods;

            int index = await GridDetail.GetRowIndexByPrimaryKeyAsync(data.OrderID);

            await GridDetail.CloseEditAsync();

            batchdata.Add(data);

            var batchChanges = new BatchChanges<Order>()

                {

                    AddedRecords = batchdata,

                };

            await GridDetail.ApplyBatchChangesAsync(batchChanges);

            await JSInterop.InvokeVoidAsync("focus");

        

        }

    }

}


Kindly get back to us if you have further queries.


Regards,

Monisha


Attachment: BlazorApp1_f0283688.zip


TY Tyrone replied to Monisha Saravanan January 15, 2025 08:35 AM UTC

thanks Monisha,

This seems working. But how can I apply this in modifying data or change added data. I also use the enter key for editing row.

this works only  for adding rows.


 await GridDetail.CloseEditAsync();

            batchdata.Add(data);

            var batchChanges = new BatchChanges<Order>()

                {

                    AddedRecords = batchdata,

                };

            await GridDetail.ApplyBatchChangesAsync(batchChanges);



Thanks and Best Regards,


Tyrone





SK Sanjay Kumar Suresh Syncfusion Team January 16, 2025 04:25 PM UTC

Hi Tyrone,


Query: how can I apply this in modifying data or change added data


We have customized the code in the provided sample to meet your requirement for editing scenarios. By checking whether the entered primary key already exists in the Grid, we can determine if the user is attempting to modify existing data or add new data. This logic has been implemented to achieve your requirement successfully.


Concern Code Snippet:


List<Order> batchdata = new List<Order>();

List<Order> batchModifieddata = new List<Order>();

….

if (GridDetail.DataSource.Where(e => e.OrderID == data.OrderID).Any()){

    batchModifieddata.Add(data);

}

else

{

    batchdata.Add(data);

}

var batchChanges = new BatchChanges<Order>()

    {

        AddedRecords = batchdata,

        ChangedRecords = batchModifieddata,

    };


We have attached a sample for additional reference. Please take a look and let us know if you have any questions.



Regards,

Sanjay Kumar Suresh


Attachment: BlazorApp1_6c6812e0.7z


TY Tyrone replied to Sanjay Kumar Suresh February 27, 2025 05:22 AM UTC

Hi  Sanjay Kumar Suresh,


Thanks for the reply.  There is a case that I need to alter an added item. but it only keeps on adding an another item instead of updating it.. 

Add1.PNG

Add2.PNG

Add3.PNG

I tried this but no avail. Add3.PNG


 var modifiedOrder = batchModifieddata.FirstOrDefault(o => o.OrderID == updatedOrder.OrderID);
    
    if (modifiedOrder != null)
    {
        // Update properties of the existing modified order
        modifiedOrder.CustomerID = updatedOrder.CustomerID;
        modifiedOrder.Freight = updatedOrder.Freight;
        modifiedOrder.ShipCountry = updatedOrder.ShipCountry;
        modifiedOrder.FreeGoods = updatedOrder.FreeGoods;
    }
    else
    {
        // If not found in modified records, check in the batchdata
        var existingOrder = batchdata.FirstOrDefault(o => o.OrderID == updatedOrder.OrderID);
        
        if (existingOrder != null)
        {
            // Update properties of the existing order
            existingOrder.CustomerID = updatedOrder.CustomerID;
            existingOrder.Freight = updatedOrder.Freight;
            existingOrder.ShipCountry = updatedOrder.ShipCountry;
            existingOrder.FreeGoods = updatedOrder.FreeGoods;
        }
        else
        {
            // If not found in either, add it to batchdata
            batchdata.Add(updatedOrder);
        }
    }



Do I need to add another ID column which is incremental in order to identify if the selected column is newly added?


Thanks for the help and Best Regard,


Tyrone



SK Sanjay Kumar Suresh Syncfusion Team February 27, 2025 10:33 AM UTC

Hi Tyrone,


We have successfully reproduced the scenario in our sample. It appears that the problem arises because the data source does not contain any records, resulting in an empty grid in your particular situation.


To resolve this, we recommend validating using the List<object> we maintain for the added records. This approach should meet your requirements effectively. Please review the optimized code below:


Code Snippet:


if (batchdata.Count > 0 && batchdata.Where(e => e.OrderID == data.OrderID).Any()) // if it’s the same primary key it will get into modified data.

{

    batchModifieddata.Add(data);

}

else

{

    batchdata.Add(data);

}


We have attached a sample for additional reference. Please take a look and let us know if you have any questions.


Regards,

Sanjay Kumar Suresh


Attachment: BlazorApp1_2ccc1344.7z


SK Sanjay Kumar Suresh Syncfusion Team February 27, 2025 10:34 AM UTC

Please refer the concern video demo after fix here.



Attachment: AfterFix_51cf2799.7z


TY Tyrone February 27, 2025 03:42 PM UTC

Hi Sanjay,


Thanks for immediate reply.. I'll give it a try.


Btw, is there is a way to assign incremental ID automatically for an added item. (after click of "add" button). 

Thanks and best regards,


Tyrone




TY Tyrone replied to Sanjay Kumar Suresh February 27, 2025 10:53 PM UTC

Hi Sanjay,


I already reviewed your code. It Addresses the concern, but there is conflict in saving data.. I want to keep the new item as AddedRecord so it will classify as Create instead of Update when writing to database. 


Here is my code for saving data for line items.



//Under saveheader() method 'await GridDetail.EndEditAsync();' is the method that triggers to call savedetail..


 public async Task SaveDetail(BeforeBatchSaveArgs<DeliveryReceiptsDetailEdit> Args)

 {


 foreach (var DRdetailNew in Args.BatchChanges.AddedRecords)

    {


            DRdetail.OrderId = DRdetailNew.OrderId;

            DRdetail.ItemId = DRdetailNew.ItemId;

            DRdetail.Quantity = DRdetailNew.Quantity;

            DRdetail.UnitCost = DRdetailNew.UnitCost;

            DRdetail.FreeGoods = DRdetailNew.FreeGoods;


            await DRdetailService.CreateDRdetail(DRdetail);

     }


    foreach (var DRdetailNew in Args.BatchChanges.ChangedRecords)

    {

      DRdetail.OrderId = DRdetailNew.OrderId;

            DRdetail.ItemId = DRdetailNew.ItemId;

            DRdetail.Quantity = DRdetailNew.Quantity;

            DRdetail.UnitCost = DRdetailNew.UnitCost;

            DRdetail.FreeGoods = DRdetailNew.FreeGoods;

            await DRdetailService.UpdateDRdetail(DRdetail);

    }



    foreach (var DRdetailNew in Args.BatchChanges.DeletedRecords)


    {


        await DRdetailService.DeleteDRdetail(Convert.ToInt32(DRdetailNew.DrdetailId));


    }

}


Best Regards,


Tyrone



SK Sanjay Kumar Suresh Syncfusion Team February 28, 2025 03:03 PM UTC

Hi Tyrone,


Query 1: Is there is a way to assign incremental ID automatically for an added item. (after click of "add" button). 


Regarding the above query the separate forum was created from your end, and we have updated the solution on the convern forum please use the concern forum for queries related to the increment topic while Add action.


Concern Forum link: https://www.syncfusion.com/forums/196228/incremental-row-id


Query 2: There is conflict in saving data.. I want to keep the new item as AddedRecord so it will classify as Create instead of Update


Before proceeding with the reported requirement, we require some additional clarification from your end. Please share the below details to proceed further at our end.


  1. Share us the simple issue replicating sample at your end.
  2. Share us the video demonstration of the reported behavior.
  3. Please share your requirement and the behavior you are trying to achieve ?


The above requested detail will be very helpful for us to validate the reported issue at our end.


Regards,

Sanjay Kumar Suresh



TY Tyrone replied to Sanjay Kumar Suresh February 28, 2025 10:28 PM UTC

Hi Sanjay,


I think I already got my solution with the info's you provided me. I just need to identify the added records and modified record before writing them in data in batch. incremental ID plus OrderID will do it. 


Thanks a lot and regards,


Tyrone



NP Naveen Palanivel Syncfusion Team March 3, 2025 06:34 PM UTC

Hi Tyrone,


Thank you for your update. We’re glad the provided response was helpful to you.


We reviewed your query, and you can automatically assign new values to the primary key column using the DefaultValue property in the GridColumn. This property ensures that newly added rows receive a predefined value, making data entry more efficient. Since your scenario involves batch editing, you can achieve this by handling the OnBatchAdd event. This event allows you to dynamically assign and increment values for the primary key column when new rows are added. Whenever the Add button is clicked, the OnBatchAdd event is triggered, allowing you to determine whether a new record has been added. Please refer to the following code snippet for implementation.


Concern Code Snippet:


<GridEvents OnBatchAdd="BatchAddHandler" TValue="Order"></GridEvents>

….

 

int incer = 16;

 

    public void BatchAddHandler(BeforeBatchAddArgs<Order> args)

    {

         args.DefaultData.OrderID= incer++;

    }

 


Playground Sample:

https://blazorplayground.syncfusion.com/embed/VXBJMiVaqdDHZvUN?appbar=true&editor=true&result=true&errorlist=true&theme=bootstrap5


Additional References:

https://blazor.syncfusion.com/documentation/datagrid/events#onbatchadd


Please get back to us if you need any other assistance.


Regards,

Naveen


Loader.
Up arrow icon