DataGrid cells can be selected using mouse by simply clicking and dragging over the cells. Pressing Cmd / Ctrl key during selection will add to existing selections. Pressing Shift key allows selection of regions between two clicks.
DataGrid supports three modes of selection 'cell', 'row', 'column'. In order to disable selections, selection mode can be set to 'none' which is the default setting.
from ipydatagrid import DataGrid
from json import load
import pandas as pd
with open("./cars.json") as fobj:
data = load(fobj)
df = pd.DataFrame(data["data"]).drop("index", axis=1)
datagrid = DataGrid(df, selection_mode="cell")
datagrid
Select a rectangular region programmatically. 'row1' & 'column1' correspond to top-left corner of selected region, and 'row2'& 'column2' correspond to bottom-right corner of selected region. Row and column values start from 0 and from top-left corner of grid body. clear_mode specifies how new selection should be applied in the presence of other selections. possible values are 'none'
: to keep previous selections (default), 'all'
: to clear previous selections, 'current'
: to remove only the last selection pre-existing
datagrid.select(row1=1, column1=1, row2=2, column2=2, clear_mode="all")
Clear existing selections
datagrid.clear_selection()
datagrid.select(1, 1, 2, 2)
datagrid.select(2, 2, 3, 3)
Select individual cells by using only row1 and column1 parameters
datagrid.select(4, 1)
datagrid.select(6, 1, clear_mode="current")
Selections are stored as rectangular regions internally and can be accessed using:
datagrid.selections
Access cells selected. Cells in overlapped regions are listed once.
datagrid.selected_cells
Cell values for the selected cells can also be accessed with single method call
datagrid.selected_cell_values
For large DataGrids and large selection regions, it is more optimal to use iterator and access selected cells one by one. selected_cell_iterator can be used to loop through selected cells without need to store them into a list in advance internally.
for cell in datagrid.selected_cell_iterator:
print(cell)
Iterator also provides the total selection count
len(datagrid.selected_cell_iterator)
DataGrid selections can also be modified with a single assignment statement by passing in selection regions as a list of rectangles.
datagrid.selections = [
{"r1": 22, "r2": 20, "c1": 0, "c2": 2},
{"r1": 6, "r2": 6, "c1": 2, "c2": 2},
{"r1": 10, "r2": 10, "c1": 3, "c2": 3},
{"r1": 13, "r2": 13, "c1": 2, "c2": 2},
]