Row Selection

To enable rows selection, set the Grid Option rowSelection to either 'single' or 'multiple':

Moreover, it is also possible to use the following Grid Options to fine-tune the row selection behavior:

Row Selection Options Example

The following example shows the Grid behavior using the different Grid Options to select the rows.

Using rowSelection='single':

Using rowSelection='multiple':

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, callback, Patch
import pandas as pd
import json

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]

app.layout = html.Div(
    [
        dcc.RadioItems(
            id='radio-row-selection-type',
            options={'single': 'Single Row Selection', 'multiple': 'Multi Row Selection'},
            value='single'
        ),
        dcc.Checklist(
            id='chk-row-selection-options',
            options=[
                {'label': 'Enable Multi Row Selection On Click', "value": 'rowMultiSelectWithClick'},
                {'label': "Disable deselection holding 'Ctrl'", "value": 'suppressRowDeselection'}
            ],
            value=[]
        ),
        html.Pre(id="pre-row-selection-options"),
        dag.AgGrid(
            id="row-selection-options",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={"animateRows": False}
        ),
    ],
)


@callback(
    Output("row-selection-options", "dashGridOptions"),
    Output("pre-row-selection-options", "children"),
    Input('radio-row-selection-type', "value"),
    Input('chk-row-selection-options', "value")
)
def set_grid_options(row_selection, selected_options):
    grid_options = {
        "rowSelection": row_selection,
        "rowMultiSelectWithClick": row_selection == 'multiple' and 'rowMultiSelectWithClick' in selected_options,
        "suppressRowDeselection": 'suppressRowDeselection' in selected_options,
    }
    output = {k: v for k, v in grid_options.items() if v is not False}

    return grid_options, f'dashGridOptions = {json.dumps(output, indent=2).replace("true", "True") if selected_options else output}'


@callback(
    Output("chk-row-selection-options", "options"),
    Output("row-selection-options", "selectedRows"),
    Input('radio-row-selection-type', "value")
)
def disable__checkbox(row_selection):
    options_patch = Patch()
    options_patch[0]['disabled'] = row_selection == 'single'
    return options_patch, []


if __name__ == "__main__":
    app.run(debug=True)

   

Specify Selectable Rows

It is possible to specify which rows can be selected via the isRowSelectable function.

For instance if we only wanted to allow rows where the ‘year’ field is more than 2007, we could implement the
following:

dashGridOptions = {
    'rowSelection': "multiple",
    'isRowSelectable': {"function": "params.data.year > 2007"}
}

Note that it can be a good idea to use checkbox selection to help to identify the selectable rows as the checkbox of the
non-selectable rows will be hidden, see
example Selectable Rows with Checkboxes.

The following example shows the result setting the above parameters, only rows having year > 2007 are selectable. The
multi-rows selection is enabled, try to select a range of rows using <kbd>Shift<kbd>, only the selectable rows will be
selected.

import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-selectable-rows",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={
                "rowSelection": "multiple",
                "isRowSelectable": {"function": "params.data.year > 2007"},
                "animateRows": False
            }
        ),
    ],
)

if __name__ == "__main__":
    app.run(debug=True)

selectedRows Parameter

The Grid parameter selectedRows can be used to:

The selectedRows parameter can be set 3 ways:

Note that selecting hundreds of rows using rowData of the rows to select can show lags, setting getRowId can improve
the performance. Using row ids or a function to select hundreds of rows generally provides even better performance.
See Improve Selection Performance.

Simple Example

In the following example selectedRows is used:

import dash_ag_grid as dag
from dash import Dash, html, Input, Output, callback
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]

app.layout = html.Div(
    [
        html.Button("Select 'Natalie Coughlin' rows", id="btn-row-selection-selected-rows"),
        dag.AgGrid(
            id="row-selection-selected-rows",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple", "animateRows": False},
            selectedRows=df.head(5).to_dict("records")
        ),
        html.Pre(id="pre-row-selection-selected-rows", style={'text-wrap': 'wrap'})
    ],
)


@callback(
    Output("pre-row-selection-selected-rows", "children"),
    Input("row-selection-selected-rows", "selectedRows"),
)
def output_selected_rows(selected_rows):
    selected_list = [f"{s['athlete']} ({s['year']})" for s in selected_rows]
    return f"You selected the athlete{'s' if len(selected_rows) > 1 else ''}:\n{', '.join(selected_list)}" if selected_rows else "No selections"


@callback(
    Output("row-selection-selected-rows", "selectedRows"),
    Input("btn-row-selection-selected-rows", "n_clicks"),
    prevent_initial_call=True,
)
def select_rows(_):
    return df[df['athlete'] == 'Natalie Coughlin'].to_dict("records")


if __name__ == "__main__":
    app.run(debug=True)

This second example shows how to generate a popup using Dash Bootstrap Components when a user selects a row in the
grid.

import dash_ag_grid as dag
from dash import Dash, Input, Output, html, ctx, no_update, callback
import dash_bootstrap_components as dbc

app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB])


columnDefs = [{"field": i} for i in ["make", "model", "price"]]


rowData = [
    {"make": "Toyota", "model": "Celica", "price": 35000},
    {"make": "Ford", "model": "Mondeo", "price": 32000},
    {"make": "Porsche", "model": "Boxster", "price": 72000},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-popup-popup",
            rowData=rowData,
            columnDefs=columnDefs,
            columnSize="sizeToFit",
            dashGridOptions={"rowSelection": "single", "animateRows": False},
        ),
        dbc.Modal(
            [
                dbc.ModalHeader("More information about selected row"),
                dbc.ModalBody(id="row-selection-modal-content"),
                dbc.ModalFooter(dbc.Button("Close", id="row-selection-modal-close", className="ml-auto")),
            ],
            id="row-selection-modal",
        ),
    ]
)


@callback(
    Output("row-selection-modal", "is_open"),
    Output("row-selection-modal-content", "children"),
    Input("row-selection-popup-popup", "selectedRows"),
    Input("row-selection-modal-close", "n_clicks"),
)
def open_modal(selection, _):
    if ctx.triggered_id == "row-selection-modal-close":
        return False, no_update
    if selection:
        return True, "You selected " + ", ".join(
            [
                f"{s['make']} (model {s['model']} and price {s['price']})"
                for s in selection
            ]
        )

    return no_update, no_update


if __name__ == "__main__":
    app.run(debug=True)

Improve Selection Performance

This example shows the selection performance selecting hundreds of rows when setting selectedRows with the following
options:

The button can be used to select/unselect the rows, and we can see the time to perform the selection.

Note that the function used in this example {'function': 'params.data.age == 23'} selects 691 rows. To compare the
results, the other options are also set to select 691 rows.

The first option can take a few seconds to perform the selection. The second greatly improves the performance.
The third and the final options provide even better performance.

import dash_ag_grid as dag
from dash import Dash, html, Input, Output, callback, dcc, no_update, State
import pandas as pd
import time

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
df["id"] = df.index

columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]

app.layout = html.Div(
    [
        html.Button("Select Rows", id="btn-row-selection-performance"),
        dcc.RadioItems(
            id='radio-row-selection-performance',
            options={
                'rowdata': "selectedRows = df.head(691).to_dict('records')",
                'rowdata+getrowid': "selectedRows = df.head(691).to_dict('records') and getRowId = 'params.data.id'",
                'ids': "selectedRows = {'ids': [str(i) for i in range(691)]}",
                'function': "selectedRows = {'function': 'params.data.age == 23'}",
            },
            value='rowdata',
            style={'margin': '10px 0px'}
        ),
        html.Div('Timer: 0s', id='div-row-selection-performance'),
        dag.AgGrid(
            id="row-selection-performance",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple", "animateRows": False},
        ),
        dcc.Store(id="store-row-selection-performance")
    ]
)


@callback(
    Output("row-selection-performance", "selectedRows"),
    Output("row-selection-performance", "getRowId"),
    Output("btn-row-selection-performance", "children"),
    Output("store-row-selection-performance", "data"),
    Input("btn-row-selection-performance", "n_clicks"),
    State("radio-row-selection-performance", "value"),
    prevent_initial_call=True,
)
def select_deselect_rows(n, value):
    if n % 2 == 0:
        return [], no_update, "Select Rows", no_update
    else:
        get_row_id = None
        if 'rowdata' in value:
            selected_rows = df.head(691).to_dict("records")
            get_row_id = "params.data.id" if 'getrowid' in value else None
        elif value == 'ids':
            selected_rows = {"ids": [str(i) for i in range(691)]}
        else:
            selected_rows = {"function": "params.data.age == 23"}
        return selected_rows, get_row_id, "Deselect Rows", time.time()


@callback(
    Output("div-row-selection-performance", "children"),
    Input("row-selection-performance", "selectedRows"),
    State("store-row-selection-performance", "data"),
    prevent_initial_call=True,
)
def update_timer(selected_rows, start_time):
    return f'Timer: {(time.time() - start_time):.3f}s' if selected_rows else no_update


if __name__ == "__main__":
    app.run(debug=True)
Timer: 0s

Remove Selected Rows

Dash AG Grid provides the deleteSelectedRows parameter that can be used to easily remove the selected rows. When set to
True under the hood it will trigger
a transaction gridApi.applyTransaction({remove: selection})

In the following example, try to select a few rows and then click on the button to remove them.

import dash_ag_grid as dag
from dash import Dash, html, Input, Output, callback
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)


columnDefs = [{"field": i} for i in ["country", "year", "athlete", "age", "sport", "total"]]

app.layout = html.Div(
    [
        html.Button("Remove Selected Rows", id="btn-row-selection-remove"),
        dag.AgGrid(
            id="row-selection-remove",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple"},
        ),
    ]
)


@callback(
    Output("row-selection-remove", "deleteSelectedRows"),
    Input("btn-row-selection-remove", "n_clicks"),
    prevent_initial_call=True,
)
def remove_selected_rows(_):
    return True


if __name__ == "__main__":
    app.run(debug=True)