Handling the onclick event from a button created dinamically

Hyuga

Freshman
Joined
Jul 21, 2005
Messages
30
Situation:
I have a form with a left menu, this menu has 5 LinkButtons. Depending on the option clicked, in the right side of the form it should appear different controls, that I will create dinamically.

The Problem:
Appeared when I have to handle the events generated from the dinamically generated controls. In concrete, with one of the options I create a button that, when the user clicked it, has to clear the placeholder and put some other things inside it (text, controls, whatever).

The code:
Visual Basic:
Private WithEvents bActual As Button

Sub Page_Load(sender As Object, e As EventArgs)
    bActual = New Button()
    AddHandler bActual.Click, AddressOf MuestraForm
End Sub

Sub MostrarSTgrupo(sender As Object, e As System.EventArgs)
    ' boton para crear tareas
    'Fijamos las propiedades
    bActual.id = "bCrearTarea"
    bActual.Text = "Crear Nueva Tarea"

    listadoTareas.Controls.Add(bActual)
End Sub

Sub MuestraForm(sender As Object, e As System.EventArgs)
    mensaje.text="Vamos a mostrar el formulario"
End Sub

and the html "interesting" part:
Visual Basic:
<body>
    <form runat="server">
    <div id="menu">
        <h5>Supervisión de Tareas</h5>
        <ul>
            <li class="enlaces"><asp:LinkButton id="STgrupo" Text="De Grupo" onClick="MostrarSTgrupo" runat="server" /></li>
        </ul>
    </div>
    <div id="controles">
        <asp:PlaceHolder id="listadoTareas" runat="server"></asp:PlaceHolder>
        <asp:Label id="mensaje" runat="server" />
    </div>
    </form>
</body>

Notes:
I've declared the variable button as global to add the WithEvents clause, and I've created the button and declared his event handler in Page_Load because I've read that the binding of the event form the control and his event handler should be done there.


Any idea or corrections to this pieces of code will be appreciated, thanks everybody!
 
The code from your "MostrarSTgrupo" Sub needs to be executed as part of the Page_Load.

The ID needs to be set and added back into the forms controls collection before it will fire the events. Otherwise, the rest looks OK.
 
Wayneph, thanks for the answer ;)

wayneph said:
The code from your "MostrarSTgrupo" Sub needs to be executed as part of the Page_Load.

I don't want to execute this code until it is needed, I only want to create the button when the user clicked one of the options of my menu. So it should be created after the Page_Load event, when handling with postback events.
 
Back
Top