Custom Control Postback Problems
(Thursday, December 23, 2004)
Found the following interesting discussion in the Newsgroups:
Custom Control Postback Problems by:BluDog
| Hi
I have a created a custom web control called ImageBrowser, extract is below:
<Code>
#Region "Properties"
Public Property Images() As ImageCollection Get If ViewState("Images") Is Nothing Then ViewState("Images") = New ImageCollection End if Return CType(ViewState("Images"), GalleryImageCollection) End Get Set(ByVal Value As ImageCollection) ViewState("Images") = Value End Set End Property
Public Property CurrentImage() As Integer Get Return CInt(ViewState("CurrentImage")) End Get Set(ByVal Value As Integer) ViewState("CurrentImage") = Value End Set End Property
#End Region
#Region "Initilization"
Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
If Not IsPostBack Then GetData() 'populates Images collection from database
AddImages()
End Sub
Private Sub AddImages
Dim Image as WebControls.Image Dim ImageCounter as Integer For Each Image in Images Dim ImageButton as New WebControls.ImageButton ImageButton.ImageUrl = Image.ImageUrl ImageButton.ID = "Image" & ImageCounter.ToString Me.Controls.Add(ImageButton) AddHandler ImageButton.Click, AddressOf Image_Click ImageCounter += 1 Next
End Sub
#End Region
#Region "Implementation"
Private Sub Image_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim ImageName As String = CType(sender, ImageButton).ID CurrentImage = CInt(ImageName.Substring(5))
End Sub
#End Region
</Code>
Within the AddImages function each image in the Images collection is added to the control as an ImageButton, I have to do this in the prerender because i need to know what the CurrentImage property is from the ViewState and this in the first place i have found it to be populated.
The only problem is that the event for the ImageButton.Click is not firing, i believe this is because i have added it to late in the page life cycle. This appears to be a but of a nasty circle. Does anyone know where i am going wrong?
Thanks
Blu
| | | Reply: by:Raterus
| | | Eww..
Yeah I think you know your problem already, you need to call AddImages from page_load and not PreRender. By PreRender it is one step too late to process Handlers, as that step just passed.
Here is a good article on the ASP.NET page lifecycle, it may help understanding when viewstate gets populated, I don't see why you couldn't do it in page_load, perhaps you could share your problems when you try that next.
http://www.15seconds.com/Issue/020102.htm
Happy Coding! --Michael
|
|
0 Comments:
Post a Comment