Listbox: Something's wrong with my algorithm

I am trying to fill a Listbox from left to right. The data is in a one-dimensional String array. I currently get an OutOfBoundsException and do not recognize my error.

For reasons I insert the lines before filling the cells. Just in case someone asks why I don’t use Listbox.AddRow!

' Var cells() As String = Array(...)
Var row As Integer

' Loop over Cells-Array.
For cell As Integer = 0 To cells.LastRowIndex
  If cell Mod Me.ColumnCount = 0 Then    
    row = row + 1
  End If
  Me.CellValueAt(row, 0) = Cells(cell)

Does anyone see where I am wrong?

EDIT: Sample Project


Does the columncount match the size of cells() ?

Also possibly:

Me.CellValueAt(row, cell) = Cells(cell)

Nope. The Listbox.ColumnCount is set dynamically by the Width of the Listbox.

And my second point? Looks to me like you put everything in column 0.

1 Like

For now yes, because Listbox.ColumnCount isn’t the same as the cell index.

I’ve added a link to the sample Project in my initial post.

A quick test I threw together that works:

var values() as String
for intCycle as Integer = 0 to 100
  values.AddRow( intCycle.ToString )

var x as Integer
var xMax as Integer = me.ColumnCount
var intMax as Integer = values.LastRowIndex

for intCycle as Integer = 0 to intMax
  if intCycle mod xMax = 0 then
    me.AddRow( values(intCycle) )
    x = 0
    x = x + 1
    me.CellValueAt( me.LastAddedRowIndex, x ) = values(intCycle)
  end if

Updated with working code.

1 Like

Thanks @Anthony_G_Cyphers. That’s nice, but not ideal with my background.

If you take a look at my Sample Project, you’ll see, UpdateColumns is called within the Listbox.CellBackgroundPaint-Event. I need to do this, because my Listbox ist a Subclass of a Listbox and I don’t want do Re-Fill the Listbox outside (via e.g. Window Method).

The Problem is, if I call Listbox.RemoveAllRows within UpdateColumns, it raises the exception, since it is called from the Event. That’s why within the loop Listbox.AddRow is actually out of question for me and I try to do this with Listbox.CellValueAt. How do we need to modify you code to work well in my Sample Project?

EDIT: BTW, maybe you have another suggestion for speed optimisation, as I think, it’s could become very slow to re-fill the columns via Listbox.CellValueAt.

In method ‘UpdateColumns’ line number 50

For cell As Integer = 0 To cells.LastRowIndex - 1
instead of
For cell As Integer = 0 To cells.LastRowIndex

Could that solve your problem ?


Sadly it doesn’t fix the Exception. I’ve now startet to write a custom Control, to solve this.

You can’t modify the contents of the listbox from the Paint events. As you obviously discovered.