anmcgrath / BlazorDatasheet

Simple excel-like datasheet Blazor component
MIT License
131 stars 31 forks source link

Help - Code example of ObjectEditor, how can I add a new or delete an old item? #65

Closed kamazheng closed 1 month ago

kamazheng commented 2 months ago

@page "/ObjectEditor"
@using BlazorDatasheet.Render
@using BlazorDatasheet.SharedPages.Data
@using BlazorDatasheet.Core.Formats
@using BlazorDatasheet.Core.ObjectEditor
@using BlazorDatasheet.Core.Validation

<PageTitle>Object editor</PageTitle>

<h1>Object Editor</h1>

<p>This example shows one method of using metadata and cell change events to create an object property editor for a set of objects.</p>

<p>In this example we have a datasource of 100 people and set up a page size of 10. When the page is changed, the Sheet data is overidden from the new data.</p>

<Datasheet
    @ref="dataSheet1"
    CustomCellTypeDefinitions="CustomTypes"
    Sheet="editor.Sheet">
</Datasheet>

<p>Page @(editor.CurrentPage + 1) of @editor.NumPages</p>

<button @onclick="() => editor.SetPage(editor.CurrentPage - 1)">Previous Page</button>
<button @onclick="() => editor.SetPage(editor.CurrentPage + 1)">Next Page</button>
<button @onclick="() => addNewPeople()">Add New One</button>

@code {

    private List<Person> People;
    private ObjectEditor<Person> editor;
    private Datasheet dataSheet1;
    private Dictionary<string, CellTypeDefinition> CustomTypes { get; } = new();

    protected override void OnInitialized()
    {
        People = new List<Person>();
        var r = new Random();
        for (int i = 0; i < 20; i++)
        {
            People.Add(new Person() { Id = i + 1, FirstName = "Person " + i, LastName = "LastName " + i, Age = (r.Next(90) + 10).ToString() });
        }

        var builder = new ObjectEditorBuilder<Person>(new EnumerableQuery<Person>(People))
     .WithRowHeadingSelector(x => x.Id.ToString())
     .WithPageSize(10)
     .WithProperty(x => x.FirstName)
     .WithProperty(x => x.LastName)
     .WithProperty(x => x.Age,
         x =>
             x.WithDataValidator(new NumberValidator(true))
     ).WithProperty(x => x.IsFriendly,
         x =>
             x.WithType("boolean"));
        editor = builder.Build();

        base.OnInitialized();
    }

    private void addNewPeople()
    {
        People.Add(new Person{
            Id = People.Count + 1, FirstName = "New Person " + People.Count, LastName = "LastName " + People.Count, Age = "20" });
        // TODO:  Rebuild the editor
        // How?

    }

}
anmcgrath commented 1 month ago

Hi @kamazheng the object editor is just an example of how to display/edit data, so it's not fully fleshed out. You would need to extend the class and add methods for inserting/removing data, which would then insert/remove rows in the sheet.