Add an event handler to an arraylist

  • Thread starter Thread starter Peter
  • Start date Start date
P

Peter

I have looked high and low for an example of adding an eventhandler to
an arraylist. I want a method to fire every time a item is added to
an arraylist. Any sample code would be appreciated.

IE. Dim myArrayList as new Arraylist
myArrayList.add("StringData") ---------->EventFires

Msgbox("A Record has been added.")

Thanks,


Peter
 
You can't add an event handler the way you've mentioned. However, you can
inherit from the ArrayList class and add an event which you can raise when
an item is added. Here's how:

Public Class ArrayListEx
Inherits ArrayList

Public Event ItemAdded(ByVal Index As Integer)

Public Overrides Function Add(ByVal value As Object) As Integer
Dim ReturnValue As Integer = MyBase.Add(value)
RaiseEvent ItemAdded(ReturnValue)
Return ReturnValue
End Function
End Class

Private WithEvents oArr As New ArrayListEx

Private Sub TestSub()
oArr.Add(123)
oArr.Add("test")
End Sub

Private Sub oArr_ItemAdded(ByVal Index As Integer) Handles oArr.ItemAdded
MessageBox.Show("Index of Item Added: " & Index)
End Sub

Now just call TestSub from anywhere and you'll see a message box pop up
whenever an item is added to the ArrayList.

hope that helps..
Imran.
 
Peter,

Peter, there can in my opinion only be one reason when you want to use an
event on an array and that is when you have binded something (in whatever
way) to that array using a sealed class.

That will be a lot of work, and the sample from Imran shows how, but using
the datatable in that case give that direct.

An other reason can be that someone lost the control over his code. However
using it than leads more and more to spagetti code.

Therefore I am curious in what situation you want to use this?

Cor
 
I have multiple threads writing to a public arraylist. The additions
come back in different intervals (Data Queries against routers). When
data comes back I update another form with the results.

I ened up adding a raiseevent right after the .add function. This
seems to work great. I'm still open for better solutions though.

-Peter
 
Peter,

In my opinion is than the event from the router. That gives you than as well
the information to add to the arraylist. In my opinion will that even make
it possible when you pass the information using that event to do it without
a synclock, however this is just a suggestion (idea).

Cor
 
Back
Top