Ag-grid : get column index of clicked cell

Hi all,
I am trying to get the index of a cell when clicked. I am able to get the row using the return of AgGrid. I am also able to get the row and the column of the clicked cell using JS code but I cannot send the data to the streamlit code.

import streamlit as st
import numpy as np
import pandas as pd

from st_aggrid import AgGrid, DataReturnMode, GridUpdateMode, GridOptionsBuilder, JsCode

@st.cache()
def generate_df():
    df = pd.DataFrame(
        np.random.randint(0, 100, 30).reshape(-1, 3), columns=list("abc")
    )
    return df

data = generate_df()


gb = GridOptionsBuilder.from_dataframe(data)
gb.configure_columns(list('abc'), editable=True)


js = JsCode("""
function(e) {
    let api = e.api;
    let rowIndex = e.rowIndex;
    let col = e.column.colId;
    
    let rowNode = api.getDisplayedRowAtIndex(rowIndex);
    
    console.log("column index: " + col + ", row index: " + rowIndex);
};
""")

gb.configure_grid_options(onCellClicked=js)
gb.configure_selection(selection_mode ='single')
go = gb.build()

return_ag = AgGrid(data, gridOptions=go, allow_unsafe_jscode=True, reload_data=False, update_mode=GridUpdateMode.SELECTION_CHANGED)

print(return_ag)

params returned by AgGrid:

And the console in Inspect with the correct column and row indexes:

Any suggestions?

1 Like

I’m also trying to do this but without luck

ok maybe this might help: Although I don’t get the index in the example, I am sure it might work the same way…

this part taking from code that I found here…

def aggrid_interactive_table(df: pd.DataFrame):
“”"Creates an st-aggrid interactive table based on a dataframe.

Args:
    df (pd.DataFrame]): Source dataframe

Returns:
    dict: The selected row
"""
options = GridOptionsBuilder.from_dataframe(
    df, enableRowGroup=True, enableValue=True, enablePivot=True
)
#editable = True was removed - need this to be non- editable
options.configure_side_bar()

options.configure_selection("single")
selection = AgGrid(
    df,
    enable_enterprise_modules=True,
    gridOptions=options.build(),
    update_mode=GridUpdateMode.SELECTION_CHANGED,
    allow_unsafe_jscode=True,
    height=200
)

return selection

Then In my code I have the following (I am doing a parent/child form think invoice header/line items)

get the GUID (ID) of the selected row and filter the child row based on that

if selection["selected_rows"]:
    c = selection["selected_rows"][0]["ID"]
    if c > 0:
        st.write(df3[df3['ID'] == c])

What the code is setting c = the “ID Field” i have in the parent Dataframe that is selected. I had to use 0 for the first even thought I am only allowing on selection. and From there I pass it to 2nd dataframe. I have not tried with index, but though this would help. (BTW I started with streamlit yesterday and just learning)