Search code examples
asp.netvb.netfindcontrol

FindControl Not working if its being called from a different Class


On page_Init, I am creating number of UpdatePanels and inside these UpdatePanels one Panel in each. I then use this panel to further go ahead and add other controls dynamically. For example I add number of TextBoxes and Buttons in each of these Panels. Further, I am binding a click event to all the buttons that are created dynamically. The AddressOf these click events are in another class called Events. In the Sub from the Event class, when I try to find a control, It does not seem to work.

Here is the code in the EVENT Class

Public Class Events
Inherits System.Web.UI.Page

    Public Sub Dynamic_Btn_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim SQL As New SQLControl

        Dim sTempPanel1 As UpdatePanel = FindControl("MyUpdatePanel1")
        MsgBox("MyUpdatePanel1" & ":" & (sTempPanel1 Is Nothing))

    End Sub
End Class

NOTE : If the same above sub is copy / pasted to the code behind of the page class, it works.

I know I am missing some link here. May be the FindControl is not being referenced to the page in which is should search in.


Solution

  • This is clear why it doesn't work - you are running FindControl that belong to your Events class. But the buttons are not on on Event class. Why you chose such architecture - this is different question.

    What you can do to get the panel on which your button sits is to call

    Dim b as Button = DirectCast(sender, Button)
    Dim p as UpdatePanel = = DirectCast(b.Parent, UpdatePanel)
    

    Also remember this: The method [FindControl] searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page.

    But if you really don't know exact location of the control, you can write recursive function to find it

    If you know that you have

    -- Page
       -- UpdatePanel
          -- Panel
             -- Button
    

    You can hardcode

    button.Parent.Parent ' <-- this is your update panel