Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
3.40/5 (2 votes)
See more:
I am working on windows form application.

How do i add event handlers to the controls which i have created dynamically ?
Posted
Comments
PIEBALDconsult 9-Jan-15 13:27pm    
Dynamically. If you use Improve question and add some code and other detail you might get a better response.
Philippe Mori 9-Jan-15 18:07pm    
You just have to look code generated by the designer. Anything that is possible with the designer, is possible with code.

Not a problem at all. For example:
C#
Button myButton = //..

// ...

myButton.Click += (sender, eventArgs) => {
    Button senderButton = (Button)sender; // just in case you need it,
                                          // it's just to give you the idea
    // you can also use eventArgs, useful in other events,
    // to get, for example, mouse coordinates and other
    // event-specific information
    // the type of eventArgs will be one of the types
    // derived from System.EventArgs, depending on the event
    // ...
    DoSomethingInRespondToEvent(/* ... */);
};


[EDIT]

What C# are you using? If this is C#.2, it won't understand lambda syntax, so you would need to use
C#
myButton.Click +=
    delegate(object sender, AppropriateEventArgumentsType eventArgs)  {
// ...
};


—SA
 
Share this answer
 
v4
Comments
Philippe Mori 9-Jan-15 18:06pm    
Depending on how the application works, user might have to remove handlers he have add manually.
Sergey Alexandrovich Kryukov 9-Jan-15 18:18pm    
I always advocate the design where all the events handlers are added to the invocation list of an event just once and never removed. It is a safer practice. Note that adding event handler can easily cause memory leaks. In particular, it happens due to the closure effects (http://en.wikipedia.org/wiki/Closure_%28computer_programming%29), while closures per se are perfectly fine. The practice to ad the event handlers only once eliminates these problem; the handlers are removed when the object with event instances becomes unreachable.

This is a big and massively overlooked topic, probably deserves a whole article.

—SA
BillWoodruff 9-Jan-15 21:15pm    
There are many real-world cases where removing an Event-Handler, or re-activating an Event-Handler that was in previous use, is useful, even necessary.

The only mention of Closure for C# in the Wikipedia article you cite is this: "C# anonymous methods and lambda expressions support closure."

If you want to make the claim that Event Handlers in C# WinForms programming lead to memory leaks, you need to cite other sources, or say a bit more about what in your own experience leads you to conclude this.
Sergey Alexandrovich Kryukov 10-Jan-15 2:05am    
They do. Yes, this needs a proof (and not even "other sources"), but this is a long talk. Note that this is not a part of the answer, discussion in comment. By the way, have you been aware of those leaks? If not, I would advice to learn this part...
—SA
Sergey Alexandrovich Kryukov 10-Jan-15 2:13am    
Real-word cases when removing event handler is necessary? Okay, I can see a claim here. Can you prove it? I don't know such cases. We should not consider the cases which just come from bad design, right? The existing of such cases is not so hard to prove if you are sure they exist: it would be enough to present such case. I would be interested to see one, really. If I don't know such cases, I may be just unfamiliar with them, miss something, right? So, can you really present such case? I would be much grateful. You see, I presently work with some code written by a person who also maintains that removing handler was important, but he did not convince me.
—SA
I'd like to recommend you read/study this CodeProject article: [^] to better understand Events, Delegates, EventHandlers.

Of course you can add EventHandlers to WinForm Controls you create at run-time. Here's an example that demonstrates adding CheckBoxes to a Panel named 'CBPanel:
C#
// keep track of CheckBoxes, and their Checked State
private List<checkbox> AllCheckBoxes = new List<checkbox>();

private List<checkbox> AllChecked = new List<checkbox>();

private List<checkbox> AllUnChecked = new List<checkbox>();

private CheckBox LastCBCheckedStateChanged;

public void AddCheckBoxes(Panel thePanel, int nCheckBoxes, List<string> cbText)
{
    for (int i = 0; i < nCheckBoxes; i++)
    {
        var newCheckBox = new CheckBox();

        AllCheckBoxes.Add(newCheckBox);

        newCheckBox.Text = cbText[i];
        newCheckBox.BackColor = Color.GhostWhite;
        newCheckBox.ForeColor = Color.Black;

        newCheckBox.CheckStateChanged += newCheckBox_CheckStateChanged;

        thePanel.Controls.Add(newCheckBox);
        newCheckBox.Location = new Point(20, (i * 40) + 20);
    }
}

// remove current EventHandler
private void RemoveEventHandler(EventHandler theHandler)
{
    foreach (CheckBox cbx in AllCheckBoxes)
    {
        cbx.CheckStateChanged -= theHandler;
    }
}

// reset current EventHandler
private void ResetEventHandler(EventHandler theHandler)
{
    foreach (CheckBox cbx in AllCheckBoxes)
    {
        cbx.CheckStateChanged += theHandler;
    }
}

private void newCheckBox_CheckStateChanged(object sender, EventArgs e)
{
    LastCBCheckedStateChanged = sender as CheckBox;

    AllChecked = AllCheckBoxes.Where(cbx => cbx.Checked).ToList();

    AllUnChecked = AllCheckBoxes.Where(cbx => ! cbx.Checked).ToList();

    // for testing only
    foreach (var cbx in AllChecked)
    {
        MessageBox.Show(string.Format("{0} is Checked", cbx.Text));
    }
}

// test
private void AddSomeCheckBoxes(object sender, EventArgs e)
{
    AddCheckBoxes(CBPanel,4, new List<string>{"cb 1", "cb 2", "cb 3", "cb 4"});

    // test removal of Event Handler
    RemoveEventHandler(newCheckBox_CheckStateChanged);

    // test restore EventHandler
    ResetEventHandler(newCheckBox_CheckStateChanged);
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900