Listbox format on a text value

Hi - Newby question.

I am very new to this and struggling with understanding the documentation for PaintCellBackground…

I want to look at a row in a listbox and change the colour of the background for a cell matching a text value. So I have this in the PaintCellBackground event in a listbox

if row = 0 then
  g.DrawingColor = RGB(232,235,255) //or a hexa color like &cE8EBFF
  g.FillRectangle 0, 0, g.Width, g.Height
end if

if row = 2 then
  If Me.CellTextAt(row, column ) = "True" Then
    g.DrawingColor =Color.RGB(255, 0, 0)
    g.FillRectangle(0, 0, g.Width, g.Height)
  End If

The first block works fine, but the second block throws an out of bounds exception. I cannot see what is out of bounds! I must be doing something very wrong!

PaintCellBackground occurs for each row and cell visible in the Listbox, but it also occurs for rows and cells that don’t exist. This let’s you continue to paint outside of any data rows.

If you turn on Break on Exceptions and take a look at the OutOfBoundsException when it is raised, you can see the row and column values for me.CellTextAt. Xojo draws the last column all the way to the edge, so you’ll find it’s usually the row value that’s beyond the last row in your data set.

To protect yourself from this, check that the row is within your data set before attempting to fetch the cell or row values / tags.

if row = 2 then
  if row <= me.LastRowIndex then
    // Here we're drawing the cell background for a row and column that do exist
    if me.CellTextAt(row, column) = "True" then
      // Cell value is "True"



  // Here the row is 2 but may not be an actual row that exists
  // for example, continuing to draw an alternating row background
  // beyond your data set.


Thank you so much for that - works perfectly.

I had thought that something like this was the issue, but could not find it. Although I have break on exceptions ticked, nothing really shows when you click on this when it breaks, so unable to find any details on what me.celltextat is looking at. The row and column numbers are both shown as 0 in the variables list and this what was confusing me as they exist. Am I looking at the wrong thing?

It’ll show you the line (and therefore the statement) that is causing the exception, you then have to look at the variables and see which one is problematic.

You might find it instructive to use your original code and try to track down what is out of bounds.

Rows and columns only exist after you add a row with AddRow. If you haven’t added any data to the Listbox yet, there are no rows and columns but the Paint events still occur.

Ahh - OK - Thank You

Yes - quite agree - but actually a little harder than it would first appear when the exception goes out of bounds as far as I can tell so far - but thanks.