How to Add Event Handler for Dynamically Created Controls at Runtime

Add events to controls that were added dynamically

// create some dynamic button
Button b = new Button();
// assign some event to it
b.Click += (sender, e) =>
{
MessageBox.Show("the button was clicked");
};
// add the button to the form
Controls.Add(b);

Add event handlers for runtime created controls in runtime created forms

You'd use AddHandler:

' ... run-time control is created ...
Dim btn As New Button
btn.Text = "Hello World!"
AddHandler btn.Click, AddressOf ok_click

In your existing handler, you do NOT use the "Handles" keyword on the end. If you need a reference to the button, use the "sender" parameter:

Private Sub ok_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim btn As Button = DirectCast(sender, Button)
' ... do something with "btn" ...
btn.Enabled = False
End Sub

c# event handler for multiple dynamically created control

You can attach the handler like this

finalResult_panel.MouseHover += panel_MouseHover;

private void panel_MouseHover(object sender, EventArgs e)
{

}

Alternatively you can create an anonymous delegate

finalResult_panel_MouseHover += (s,e) => {
//event code
};

These will attach the same handlers to every panel so if you need to differentiate, you can do that in the handler itself (using the sender property) or somehow differentiate before attaching the handler.

Attach event to dynamic elements in javascript

This is due to the fact that your element is dynamically created, so it is attached to the DOM later, but your addEventListener call already occurred in the past.
You should use event delegation to handle the event.

document.addEventListener("click", function(e){
const target = e.target.closest("#btnPrepend"); // Or any other selector.

if(target){
// Do something with `target`.
}
});

closest ensures that the click occurred anywhere inside the target element or is the target element itself.
This is useful if, for example, instead of your <input id="btnPrepend"/> you had a <button id="btnPrepend"><i class="icon">+</i> prepend</button> and you clicked the <i class="icon">+</i>.

jQuery makes it easier:

$(document).on("click", "#btnPrepend", function(){
// Do something with `$(this)`.
});

Here is an article about event delegation.

Assigning events to a VCL control created dynamically at runtime

A VCL event handler is expected to be a non-static member of a class. Your OnTimer handler is not a class member, it is a free-floating function instead (the namespace is not important).

The correct way to solve this issue is to create a class for your OnTimer event handler, and then instantiate that class alongside the TTimer, eg:

test.h

namespace TestSpace {
class TimerEvents {
public:
void __fastcall TimerElapsed(TObject *Sender);
};
TTimer *time;
TimerEvents time_events;
AnsiString file;
void __fastcall MyFunc(AnsiString f);
}

test.cpp

void __fastcall TestSpace::MyFunc(AnsiString f) {
TestSpace::file = f;
TestSpace::time->OnTimer = &(time_events.TimerElapsed);
TestSpace::time->Enabled = true;
}

void __fastcall TestSpace::TimerEvents::TimerElapsed(TObject* Sender) {
// 'this' is the TimerEvents object
// 'Sender' is the TTimer object
TestSpace::time->Enabled = false;
DeleteFile(TestSpace::file);
}

That being said, there is actually an alternative way to use a free-floating function as a VCL event handler like you want, by using the System::TMethod struct:

test.h

namespace TestSpace {
TTimer *time;
AnsiString file;
void __fastcall MyFunc(AnsiString f);
// NOTE: must add an explicit void* parameter to receive
// what is supposed to be a class 'this' pointer...
void __fastcall TimerElapsed(void *This, TObject *Sender);
}

test.cpp

void __fastcall TestSpace::MyFunc(AnsiString f) {
TestSpace::file = f;
TMethod m;
m.Data = ...; // whatever you want to pass to the 'This' parameter, even null...
m.Code = &TestSpace::TimerElapsed;
TestSpace::time->OnTimer = reinterpret_cast<TNotifyEvent&>(m);
TestSpace::time->Enabled = true;
}

void __fastcall TestSpace::TimerElapsed(void *This, TObject* Sender) {
// 'This' is whatever you assigned to TMethod::Data
// 'Sender' is the TTimer object
TestSpace::time->Enabled = false;
DeleteFile(TestSpace::file);
}

How to properly assign events to dynamically created buttons in c# Winforms?

Because b member will reference last created dynamic button, so clicking any buttons will remove click event handler of currently referenced button in b variable, which would be last created.

Use sender to access instance of "current" button and remove click event handler only from "current" button.

void b_Click(object sender, EventArgs e)
{
var button = sender As Button;
button.Text = counter.ToString();
button.Click -= b_Click;
counter++;
}

Don't use private member for dynamic button, but local variable

private void button1_Click(object sender, EventArgs e)
{
var button = new Button();
button.Size = new Size(50, 50);
button.Click += b_Click;
this.Controls["flowLayoutPanel"].Controls.Add(button);
}

If you need to reference collection of created button somewhere, you can access them from the controls of flow panel where buttons were added

var dynamicButtons = . 
this.Controls["flowLayoutPanel"].Controls.OfType<Button>().ToList();

Or save them to the dedicated collection (in case flow panel has other buttons)

How to add event handler to a dynamically created control in VB.NET?

You need to add something to your created PictureBox to identify them in the event handler because you can't change the signature of the click event handler adding a 'parameter'

For example, you could set the Name property

pp(i) = New GroupBox
pp(i).Name = "PictureBox" + i.ToString

then in the event handler you could recognize your picture box casting the sender object to a picturebox and grabbing the Name property.

Remember, sender is always the control that triggers the event. In your case is always one of your dinamically created PictureBoxes

Private Sub testini(sender As Object, e As System.EventArgs) 
Dim pb As PictureBox = DirectCast(sender, PictureBox)
Dim pbIdentity As String = pb.Name
.....
End Sub

How to create click event for dynamically created user controls in C#?

When you create the control, all you need to do is simply link the control to a new event:

// Dynamically set the properties of the control
btn.Location = new Point((lbl.Width + cmb.Width + 17), 5);
btn.Size = new System.Drawing.Size(90, 23);
btn.Text = "Add to Table";

// Create the control
this.Controls.Add(btn);

// Link it to an Event
btn.Click += new EventHandler(btn_Click);

Then, when you (in this case) click on the newly added button, it will call your btn_Click method:

private void btn_Click(object sender, EventArgs e)
{
//do stuff...
}


Related Topics



Leave a reply



Submit