Custom event in user control
I've got a page (aspx) that contains a usercontrol (ascx). On postback of the aspx, I'd like to read some control values in the ascx. So upon reading some good articles, I created an event in my aspx that fires on postback. The event handler is in the ascx, and simply writes the values I'm interested in to the viewstate so that the parent page can read them. The problem is my event handler never gets hit, even though I see the event is raised as I step through the code. So my code bombs when trying to read the viewstate (which is empty)
Here's what I've got in my aspx:
Partial Public Class Visitor
Inherits System.Web.UI.Page
Public Event PagePostback(ByVal sender As Object, ByVal e As System.EventArgs)
.
.
.
Private Sub SaveAssignment(ByVal e As EventArgs)
RaiseEvent PagePostback(Me, e) 'Tell usercontrol to post its control values to the viewstate
'read viewstate and save its values
End Sub
Here's what's in my ascx:
Partial Public Class GenVstr
Inherits System.Web.UI.UserControl
Protected WithEvents pageVisitor As Visitor
Public Property visitType() As String
Get
Return ViewState("visitType").ToString
End Get
Set(ByVal value As String)
ViewState("visitType") = value
End Set
End Property
Public Sub ParentPostback(ByVal sender As Object, ByVal e As EventArgs) Handles pageVisitor.PagePostback
With Me
If optVIP.Ch开发者_高级运维ecked Then .visitType = "VIP"
If optFamily.Checked Then .visitType = "Family"
If optMedia.Checked Then .visitType = "Media"
If optGuest.Checked Then .visitType = "Guest"
If optConference.Checked Then .visitType = "Conference"
End With
End Sub
Oh, did I happen to mention I'm dynamically loading the ascx? :)
I think I found the problem. It was in this line:
Public Sub ParentPostback(ByVal sender As Object, ByVal e As EventArgs) Handles pageVisitor.PagePostback
Specifically in my Handles section, "pageVisitor" is the name of the variable I declared WithEvents. Instead of handling that, I should have handled the name of my usercontrol (its ID) PagePostback event.
So it should look like this:
Public Sub ParentPostback(ByVal sender As Object, ByVal e As EventArgs) Handles [myusercontrol's ID].PagePostback
I think you need to call addhandler on the dynamically create control when it is created.
精彩评论