views:

36

answers:

1

I have an object Order with a simple event,

Public Event ErrorOccurred(ByVal msg As String)

that I raise in the constructor like so when an order cannot be found (along w/setting a boolean error flag:

RaiseEvent ErrorOccurred("This order does not exist in the database.")
[Error] = True

I have a webform subscribed to the order's ErrorOccurred event:

Public WithEvents o As New Order

and I have an error handler method on the form:

Private Sub OnErrorOccurred(ByVal msg As String) Handles o.ErrorOccurred
    litMsg.Text = "<p class=""error-confirm"">" & msg & "</p>"
End Sub

When a textbox is changed, it autoposts back to the page and employs the following logic:

Private Sub txtOrderID_TextChanged(ByVal sender As Object,_
ByVal e As System.EventArgs) Handles txtOrderID.TextChanged
  If IsNumeric(txtOrderID.Text) Then
    If o.OrderID = 0 Then o = New Order(txtOrderID.Text)
      If Not o.Error Then
         'do stuff'
      Else 
         'error, run error handling'
      End If
      ....

When there is an error (when the Else logic is run), everything performs as expected except the event does not fire. However, since the Error flag is set to true, it means the event MUST have fired, since that line executes AFTER the RaiseEvent line.

I've tried everything I can think of, but I cannot figure out what could be wrong. I have events strewn everywhere in my project and they all work well using virtually the same structure. What could I be doing wrong here?

+2  A: 

I would say that since you are raising the event in the constructor, before you even have a reference to the object in your parent class, that you are unable to handle the event. In this case, especially with errors in the constructor, you would probably be much better off throwing an exception than to raise an event. I would be better to throw an exception, because some other code calling your class might not even handle the event, and you would most likely want to know that an error occured. Throwing exceptions is the standard way of letting the calling code know that an error occured. Events are more for optional things that the calling class may want to handle, but that it may also want to ignore.

Kibbee
so is that to say that you can't really raise events in the constructor?
Jason
thank you.... this was really helpful
Jason
That is correct, at least the way you have coded it. The only way I could get it to handle an event from the constructor, is to pass in a reference to the caller, from the callee, and add the event handler explicity, before the event was thrown.
Kibbee