Listbox Cellclick value problem

I have a simple single column Listbox populated by this code in the Open event for the listbox:

Var i As Integer = 0
for i = 1 to 100
ListBox1.Cell(ListBox1.LastIndex,0) = str(i)

I have this CellClick event for the listbox:

var chosen as string = str(Listbox1.SelectedRowValue)
MessageBox("Clicked Cell contents: " + chosen )

This works, but not as expected. The first time I click on a cell shows that chosen is blank. The debugger confirms this. chosen should of course be the value in the clicked cell

If I then choose another cell, chosen is set to the value of the previous cell clicked, not the current one, which is my problem

Can someone please help me to put this right? Many thanks

Is the first Cell 0 or 1 ?


If I remember correctly, CellClick fires before the value has changed. If you move that code to the Change event, it should work as-is.

You can also use CellValueAt to get the value of that cell.

EDIT: Just verified this for completeness. CellClick fires before the value change, Change fires after.

You can also refactor your Add code to:

for i as Integer = 1 to 100
  ListBox1.AddRow( str(i) )

Thanks for this - I’m all for brevity!

Don´t use Listbox1.SelectedRowValue for such thing. To obtain the “clicked row” of the ListBox, just use the “row” parameter passed in the CellClick event. To obtain the cell contents of the clicked one, read its ListBox.CellValueAt (row, column)

The “selected” item may differ from the clicked item. Specially if a multi selection of rows was done before.

Thanks - that works perfectly now.

The behaviour of CellClick seems a bit strange to me when the data has not changed. It is already in the LB cell and visible when I click. So why does the CellClick event not use that data?

Maybe it is something to do wiht my using Listbox1.SelectedRowValue, which Rick A says I shouldn’t!

CellClick is processed first because you can return True from that event to cancel the selection. If you do, the selected row will not change and the Change event won’t be raised.

Rick is just parroting what I said earlier:

Since the selection hasn’t changed, you should use CellValueAt with the Row parameter in CellClick.

I wouldn’t call all the refinement and explanations about why not using SelectedRowValue, and what to do to make it work, as I did, as parroting; but yes, you touched the correct point before me if that matters.

Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.