Articles in this section

Implement drag and drop functionality between ListBox and Grid in a Blazor application

This article demonstrates how to implement drag and drop functionality between a ListBox and a Grid component in a Blazor application using Syncfusion Blazor components. The example provided will show how to drag items from a ListBox and drop them into a Grid, updating both components accordingly.

Prerequisites

  • Syncfusion Blazor components installed in your project.
  • Basic knowledge of Blazor and C#.

Implementation Steps

1. Add ListBox and Grid Components

First, include the necessary Syncfusion namespaces and add the ListBox and Grid components to your Razor page.

@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Grids

<SfListBox TValue="string[]" AllowDragAndDrop="true" Scope="combined-list" DataSource="@Vehicles">
    <ListBoxFieldSettings Text="Text" Value="Id" />
    <ListBoxEvents TValue="string[]" OnDrop="Dropped"></ListBoxEvents>
</SfListBox>

<SfGrid DataSource="@Employees" Height="315px" AllowRowDragAndDrop="true">
    <GridEditSettings AllowAdding="true"></GridEditSettings>
    <GridRowDropSettings TargetID="listbox"></GridRowDropSettings>
    <!-- Grid columns here -->
</SfGrid>

2. Define Data Models

Create data models for the ListBox and Grid data sources.

public class EmployeeData
{
    public int? EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // Additional fields...
}

public class VehicleData
{
    public string Text { get; set; }
    public string Id { get; set; }
}

3. Handle the Drop Event

Implement the Dropped method to handle the OnDrop event and update the Grid and ListBox data sources.

private async void Dropped(DropEventArgs<VehicleData> args)
{
    var targetGrid = await JSRuntime.InvokeAsync<Boolean>("getTargetDetails", args.Left, args.Top);
    if (targetGrid)
    {
        args.Cancel = true;
        foreach (var val in args.Items)
        {
            Employees.Add(new EmployeeData() { FirstName = val.Id, LastName = val.Text });
        }
        await Grid.Refresh();
        await ListBoxObj.RemoveItemAsync(args.Items);
    }
}

4. JavaScript Interop for Drop Target Validation

In your _Layout.cshtml or corresponding JavaScript file, define the getTargetDetails function to check if the drop target is the Grid.

window.getTargetDetails = (Left, Top) => {
    var targetElement = document.elementFromPoint(Left, Top);
    return targetElement && targetElement.classList.contains('e-rowcell');
};

Conclusion

By following these steps, you can implement a drag and drop feature between a ListBox and a Grid in your Blazor application. This allows for a more interactive and user-friendly interface when managing data between different UI components.

Additional References

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied