Get selected row of table after sorting

I have some code that gets values from a selected row in a table, that works well as long as the table has not been sorted (clicking on a column header). Here is the code that I am using to get the values. This is on a button next to the table.

# Get the table component
tableComponent = event.source.parent.getComponent('Power Table')
table = tableComponent.getTable()

# Get the selected rows
selectedRows = table.getSelectedRows()

# Loop through the list of selected rows (will just be 1)
for r in selectedRows:
	intCell = tableComponent.data.getValueAt(r,"Int Column")
	stringCell = tableComponent.data.getValueAt(r,"String Column")

# Do something with the results
print (intCell)
print (stringCell)

That code works perfectly until the table has been sorted. Once it is sorted, this no longer works. After a sort, it doesn’t look like the underlying dataset is changed to reflect the sort. After the sort, if I choose the 6th row down, I will get the 7th (starts at 0) row from the origianl dataset.

How can I prevent this from happening?

Should / Can I rebuild the dataset after every sort? This seems like it could get a bit messy / process intensive.

Thanks,

Power tables are complicated. Here’s some code that should always get you the right rows, regardless of sorting or filtering:

from com.jidesoft.grid import TableModelWrapperUtils
lsm = self.getTable().getSelectionModel()
start = lsm.getMinSelectionIndex()
end = lsm.getMaxSelectionIndex() + 1
output = []
for row in range(start, end):
	if lsm.isSelectedIndex(row):
		output.append(row)
		
output = TableModelWrapperUtils.getActualRowsAt(root.getTable().getModel(), output, True)

I just made a slight change to your code, and I believe that you could accomplish what you want by using viewDataset instead of the data property of the Power Table component.

# Get the table component
tableComponent = event.source.parent.getComponent('Power Table')
table = tableComponent.getTable()

# Get the selected rows
selectedRows = table.getSelectedRows()

# Loop through the list of selected rows (will just be 1)
for r in selectedRows:
	intCell = tableComponent.viewDataset.getValueAt(r,"Int Column")
	stringCell = tableComponent.viewDataset.getValueAt(r,"String Column")

# Do something with the results
print (intCell)
print (stringCell)

Just bare in mind that with the viewDataset you can only process the visible columns. If you want to access hidden columns, you should be using data instead.

Hope this helps.

Nice and easy. This will work for some tables, but for many of mine, I am selecting the primary key as part of my query and hiding it for later use. I’ll try out @PGriffith’s answer or maybe just disable sorting on those tables…

Thanks.