ListBox. Event for ListCount change

I need an event for a listbox that rises when removing or adding a row. That is when ListCount changes,
I will appreciate your suggestions.

Subclass listbox. Override both AddRow methods, the InsertRow and also the RemoveRow method:

Sub AddRow(ParamArray item As String) Super.AddRow(item) RaiseEvent ListCountChanged() End // etc.

You type faster than me! Don’t forget deleteAllRows.

Thanks. I guessed it should be something like that, but I wanted to be sure I didn’t miss something obvious.

I found a simpler way. In the CellBackgroundPaint event I put this code at the beginning

static nr as Integer if nr <> me.ListCount Then 'Raise event number of rows changed nr = me.ListCount end if

It works but can you see any possible problem?

AFAIK only the visible rows are painted, so a remove/add may not cause your event to fire until the list is scrolled.

I’d go with Eli and Jim’s recommendations.

That’s great, but only if the code in the event is cheap. If it is expensive code it might slow down everything, as CellBackgroundPaint is called for every visible cell. In that case I’d try to reduce it to the upper left visible cell:

Static nr As Integer = -1 // If you want to raise the event on startup should the listbox be emtpy If row = Me.ScrollPosition And column = Me.ScrollPositionX Then If nr <> Me.ListCount Then 'Raise event number of rows changed nr = Me.ListCount End End

I’ve checked that if I remove rows that are not visible (at the end, so nothing happens) it works.
Having more than 100 rows and seeing the first 12 if I delete the last row and it works.

@Kem Yes, I can follow Eli and Jim’s recommendations, but I’d like to know if it is possible to change the numbers of rows and not fire the CellBackgroundPaint event. After checking it it seems it is not possible, but may be in the future Xojo changes the way the event is fired.

@Eli Ott [quote]That’s great, but only if the code in the event is cheap. If it is expensive code it might slow down everything, as CellBackgroundPaint is called for every visible cell.[/quote]

Well, although CellBackgroundPaint is called for every visible cell, only the “if” statement is computed since the number of rows has not changed.

Odd… I could have sworn that the listbox rendered each row only once but it seems that every visible row is drawn every time things change… even a window resize without affecting the listbox in any way.

Another issue with your code above is that using Static will cause the variable to be shared amongst multiple instances of the window and carry across closing and opening a new instance of the window. So you’re event would fire more often than needed if multiple instances were involded.

Thanks Jim. I see this problem with the static.
Anyway it’s been an interesting post for me.