Vaadin Flow 23:如何以编程方式选中Grid多行?
Vaadin Flow 23 Grid 编程实现多行选中
前提:开启Grid多选模式
默认Grid是单行选择模式,必须先切换为多选模式才能实现多行选中:
Grid<Devices> grid = new Grid<>(Devices.class); // 开启多选模式 grid.setSelectionMode(SelectionMode.MULTI); // 绑定设备数据列表 List<Devices> devices = yourDeviceList; grid.setItems(devices);
编程选中多行的两种方式
方式1:直接传入多个对象实例
使用select(T... items)方法,一次性传入多个要选中的Devices对象:
// 从数据列表中获取目标设备对象 Devices targetDevice1 = devices.get(0); Devices targetDevice2 = devices.get(2); // 选中对应行 grid.select(targetDevice1, targetDevice2);
方式2:传入对象集合
如果要选中的设备已经是一个集合,使用selectAll(Collection<T> items)方法更便捷:
List<Devices> devicesToSelect = Arrays.asList(targetDevice1, targetDevice2); grid.selectAll(devicesToSelect);
关键注意事项
- 执行时机:必须在Grid数据加载完成后调用选中方法,比如在数据绑定完成后、
afterNavigation事件中,或者调用grid.getDataProvider().refreshAll()之后,避免因数据未渲染导致选中失效。 - 对象匹配规则:Grid通过
equals()方法匹配对象,因此Devices类必须正确重写equals()和hashCode()方法,确保要选中的对象和Grid数据中的实例能被正确匹配。 - 取消选中:如需取消所有选中,调用
grid.deselectAll();取消单个对象选中,调用grid.deselect(targetDevice)。
内容的提问来源于stack exchange,提问作者Damian Związek
相关产品推荐
相关产品推荐

