Automatically generate Guid for ID column that is set as IsPrimaryKey="true" when adding new row to grid

I am using SyncFusion.Blazor v18.1.0.58

I have a Grid where the grid items have a GUID for the primary key. When I click on the Add command button, I want to automatically populate the Id column with a new Guid value so that if I later click on Delete to remove a given row, the Guid can be used to allow the delete to work on the selected row. Right now, with the Id field null, when I click on the Delete button, all rows are deleted form the grid. 

Should I use an event that fires when I click on the Add button or is there a built in way to generate the key for a new record?
If I need to use an event, which event would work the best for this need?

3 Replies 1 reply marked as answer

DA David Adler June 25, 2020 02:23 PM UTC

OK, I figured out one solution. 

On my Grid, I added a GridEvents section;

<GridEvents OnActionBegin="BeginHandler" TValue="TierPrice"></GridEvents>

Then in my code, I added the following;

        protected void BeginHandler(ActionEventArgs<TierPrice> args)
        {
            if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save)
            {
                if (args.Data.Id == Guid.Empty)
                {
                    args.Data.Id = Guid.NewGuid();
                }

            }
        }

This seems to work the way I want.



Marked as answer

RN Rahul Narayanasamy Syncfusion Team June 25, 2020 02:48 PM UTC

Hi David, 

Greetings from Syncfusion. 

We are happy to hear that you have achieved your requirement by yourself 

Please get back to us if you need further assistance. 

Regards, 
Rahul 
 



JO John August 17, 2021 03:58 PM UTC

Hi David,


   I stumbled across this post looking for a solution to the same problem, and I used your solution until I realized that it works just as well to initialize the Id field to a new Guid in the first place:


public class TierPrice 

{

   public Guid Id { get; set; } = Guid.NewGuid();

}


   This way, every newly created TierPrice object will have a unique Id to begin with.


Regards,

John


Loader.
Up arrow icon