views:

262

answers:

2

I'm on the verge of madness ...

In the application I'm actually building, I'm dealing with two dynamically-added controls that need to interact with each other, but I've reduced the problem to an as-simple-as-I-can-make-it example with the controls being statically loaded, and it still presents the same problem: a NullReferenceException when invoking the delegate. Here's the gist:

Control 1

Partial Class Control1
Inherits System.Web.UI.UserControl

Private _delClicked As System.Delegate
Public WriteOnly Property UpdateLabel() As System.Delegate
    Set(ByVal value As System.Delegate)
        _delClicked = value
    End Set
End Property

Protected Sub btnButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnButton.Click
    Dim aObj(0) As Object
    aObj(0) = 1
    _delClicked.DynamicInvoke(aObj)
End Sub
End Class

Control 2

Partial Class Control2
Inherits System.Web.UI.UserControl

Protected WithEvents Control1 As New Control1
Delegate Sub ChangeLabel(ByVal int As Integer)

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    Dim delChangeLabel As New ChangeLabel(AddressOf UpdateLabel)
    Me.Control1.UpdateLabel = delChangeLabel
End Sub

Private Sub UpdateLabel(ByVal int As Integer)
    lblLabel.Text = "Value is now " & int
End Sub
End Class

If I put a breakpoint on the line of Control2 where the Control1 delegate is assigned, I can step through and watch it get set in the Control1 object. However, when the btnButton_Click event fires, the value of _delClicked has gone back to Nothing.

Any help would be greatly appreciated. Thanks!

A: 

Put this in Page_init()

Dim delChangeLabel As New ChangeLabel(AddressOf UpdateLabel) 
Me.Control1.UpdateLabel = delChangeLabel
Kevin
You're right, it should be in init instead of load, but it still has the same result.
Blumer
+1  A: 

My guess would be that you are losing the control on the postback. A dynamically added control gets lost on the postback. Sure you re-create a control that does the same thing, but that doesn't mean your going to be able to catch the click event. But the control doesn't have it's viewstate carried over between the postbacks.

See this article on how to go about doing this

rie819