开发者

Dynamic events in a UserControl

I've created a custom UserControl using the GUI, and I can't get it to accept dynamically added events from within a custom class. Sorry if I get the exact code wrong, going from memory, but you get the gist. C# .NET 2008, Winform

I have a "container class" that stores all my information.

The main WinForm has an array of these, and they each have a summary panel. The main form also has a "work zone" that will let you access the container class.

The idea is, interacting with the CustomUserControl will cause stuff to happen within the ContainerClass. The control uses info from there, and I want it to update from withi开发者_运维知识库n there.

ContainerClass
{
    CustomUserControl tempControl;
    public ContainerClass()
    {
        //do stuff
        tempControl = new CustomUserControl([send information]);
        tempControl.Click += new Event(localClickEvent);
    }

    public void localClickEvent(object sender, Event e)
    {
        //do stuff
    } 
}

.

public class Form1
{
    public Form1()
    {
        //create several container objects
        //for each container object, get it's SummaryPanel 
        //and add it to the FlowLayoutPanel
        CustomUserControl tempControl = ContainerObject.GetCustomControl();
        flp_summaryPanel.Controls.Add(tempControl);
    }
}

When I execute this code, the dynamic event never fires. I've done this sort of thing before, but it was always with custom classes that inherited the control I needed. I've never inherited UserControl, so I suspect I left something out. I susepct this is an protection issue, but the compiler isn't catching it.

MORE INFO

This somehow got labeled as an ASP.net question. It's not, I'm using Winforms, though I never specifically said so.

One other thing that may be important: The dynamic event isn't in another control. It's in a custom class that functions as a large container object.

. .

As always, thanks so much for your help! :)


Try attaching event handler after adding control to Controls collection

public ParentControl()
{
    CustomUserControl tempControl = new CustomUserControl();
    this.Controls.Add(tempControl);
    tempControl.Click += new Event(localClickEvent);
}

It may be related to the fact that unless the control is added to NamingContainer the ClientID cannot be generated properly.


Which version of C# are you using? Try this:

public void ParentControl_Init()
{
    CustomUserControl tempControl = new CustomUserControl(); 
    this.Controls.Add(tempControl); 
    tempControl.Click += localClickEvent; 
}

public void localClickEvent(object sender, EventArgs e) 
{ 
    //do stuff 
}  

You don't want to add controls and attach events in the constructor. Look at how ASP.NET does it and you'll see why.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜