Handling events from controls within custom controls

Hi,

I have created a custom control that behaves similar to a placeholder control. In the Render control I simply render the sub-controls that have been programiatically added, like this:

protected override void Render(HtmlTextWriter writer)
{
    foreach (Control control in Controls)
    {
        control.RenderControl(writer);
    } ...

This is fine. I can programatically add a button with an event handler to this control in the code behind for my ASPX page, and it works with no problem. However, if I add a "sub-control" to my custom control, and then programatically add buttons etc to that control, my event handlers are never fired. Can someone tell me what I need to do. Here's my non-working custom control :-

 public class MattsControl : System.Web.UI.WebControls.WebControl, INamingContainer
    {
        private MattsSubControl SubControl;
        public  MattsControl()
        {
            SubControl = new MattsSubControl();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            foreach (Control control in Controls)
            {
                control.RenderControl(writer);
            }
            SubControl.RenderControl(writer);
        }
    }


    public class MattsSubControl : System.Web.UI.WebControls.WebControl, INamingContainer    
    {
        protected override void Render(HtmlTextWriter writer)
        {
            foreach (Control control in Controls)
            {
                // Any controls added to "SubControl" wil render, but their events are ignored!
                control.RenderControl(writer);
            }
        }
    }
I am attempting to use this class like this in the code behind of my web form - in this example the btn_Click method never fires :-
            Button btn = new Button();
            // .. code ommitted to set the ID and text
            btn.Click += new EventHandler(btn_Click);
            MattsControl1.SubControl.Controls.Add(btn);
I'm sure its simple - I just don't know what I need to do!

Matt Woberts
0
MattWoberts
9/10/2007 11:06:43 AM
asp.net.custom-server-controls 3498 articles. 0 followers. Follow

4 Replies
983 Views

Similar Articles

[PageSpeed] 3
Get it on Google Play
Get it on Apple App Store

I think you should write a CompositeControl rather than a WebControl. This issue should get resolved as soon as you inherit from CompositeControl and add controls to Controls collection in CreateChildControls method.

Check out the below example:

http://msdn2.microsoft.com/en-us/library/3257x3ea.aspx


- Sujit

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
sujitm
9/10/2007 11:40:37 AM

I have the same problem and that link didn't help at all, why can't I write the code that I want to be executed when users click a buttom from the class that defines it??? Angry

0
nmorales
9/10/2007 12:56:25 PM

Thanks for the response. Unfortunately, it needs to be a custom control, because I need to allow the users of the control to be able to add their own controls (buttons etc). So it needs to have behavour that is similar to something like a placeholder.

EDIT: I realised after posting this that making it a compisite control would probably not remove this functionality. So I tried making the changes (turned my main class into a composite control), and it didn't make any difference.

 


Matt Woberts
0
MattWoberts
9/10/2007 1:24:39 PM

 Aha! Fixed it

 The solution was not to make it a composite control, but I needed to make sure that my SubControl was added to my main control's list of controls, in order to allow events to bubble up nicely. This is done by overriding the CreateChildControls method. Thanks for sajit for sending me to that link with the information I needed! Heres the full code which is working nicely:-

 
 

    [ParseChildren(true)]
public class MattsControl : WebControl, INamingContainer
{
public MattsSubControl SubControl;

public MattsControl()
{
SubControl = new MattsSubControl();
}

protected override void Render(HtmlTextWriter writer)
{
foreach (Control control in Controls)
{
control.RenderControl(writer);
}
}

protected override void CreateChildControls()
{
Controls.Clear();
this.Controls.Add(SubControl);
}
}

public class MattsSubControl : WebControl, INamingContainer
{
protected override void Render(HtmlTextWriter writer)
{
foreach (Control control in Controls)
{
control.RenderControl(writer);
}
}
}
 
 
Matt Woberts
0
MattWoberts
9/10/2007 1:52:40 PM
Reply:

Similar Artilces:

Custom Control within a Control Control
I am developing a custom controls that will render headers for different web sites. Within these controls, I want to place another custom control that will change the language. I created the language control and had it implement IPostBackDataHandler. This control works fine if I drag it on a new web form, but if I tell a header custom control to render it problems occur. The Language Selector custom control does not have a Page member anymore and the event handlers do not work. Does anyone have any experience with doing something similiar? Anyone have any suggestions? Thanks, ...

problems listenening to events on a custom server control from another custom server control
 Hi all,I am having problems listening to events on one of custom server controls(AddBookmark) from another custom server control(BookmarkList). The listener or the BookmarkList control has a property that can be set to the AddBookmark control (string at design but the reference is obtained at run-time). I am able to get a reference to the AddBookmark control and add a listener to it on the BookmarkList control on the OnPrender of BookmarkList. But the problem is that when the events on AddBookmark gets fired, the listener added from the BookmarkList is no longer present and the listene...

handling events for controls in custom server control
Hi,     I am having a problem in using server controls in ASP.Net, with C#.  I am trying to create a server control which contains 2 other server controls that I created (Called MyImageButton).  MyImageButton extends the standard ImageButton with some other properties & methods that I needed.  It therefore also has the 'OnClick' event.  From the original server control, I would like to handle the Click event for these 2 image buttons in the same server control.  Basically, this server control will show 2 images, ascending and descendin...

Custom Control within a Custom Control
I have two individual custom controls say custom cc1 and cc2. cc1 is communicating to cc2 using event delegate mechanism.I have tested the behaviour by dropping cc1 and cc2 onto a Web Page and it works fine. I want to create a third custom control say cc3 which should contain both cc1 and cc2. So that if i drag and drop cc3 onto a Web Page i can acheive exactly what i am doing above. The problem is that i am not sure how to call/register a custom control within a custom control ? Any clue ? Thanks!! Hi, Do you mean adding custom control to custom control? I think you can use the same wa...

How do you expose the event of a child server control from within a custom control?
I am trying to create a custom control that has a server control (dropdownlist) as a child.  I need to be able to expose the selectedindexchanged event from the dropdownlist at the page level.  How do you do this?  Here is a quick abbreviated example I wrote to show what I am trying to do:  My Custom Control1 Public Class MyCustomControl 2 Inherits Control 3 ' Variables 4 Protected WithEvents ddlServerControl As New DropDownList 5 ' Methods 6 Private Sub MyCustomControl_Load(ByVal sender As Object, ByVal e As System...

Custom Server Control Made of Custom Controls?
I'm giving myself a crash course in custom server controls, and I have a quick general question. Can I have a custom server control that is composed of other server controls I created. I'm pretty sure the answer is yes, but I want to be positive. Yes http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondevelopingcompositecontrols.asp Shows how to combine existing controls into a new control using class composition. -ron Thanks! ASP.NET so rocks! Making page components extensible objects is such a great idea! I love it....

Usercontrol vs Custom Server Controls, Any need for Custom Server Controls
Hello I'm new to ASP.Net so this is probably a stupid question but, is there any need to create customer server controls now that you can pre-compile usercontrols into a dll and thus easily share between applications? This blog post from David Ebb describes how to do it and the restrictions he note don't seem that bad (other than being able to embed resources such as images in the dll). http://blogs.msdn.com/davidebb/archive/2005/10/30/487160.aspx His article desribes the techniques for ASP.Net 2.0 and he suggests that there will be further improvements in .Net 3.5 in this ar...

how to have both server controls and html controls rendered in a custom control?
I have a custom control in which there is an html text box.when you click on it , a div containing a table is appeared and according to what you select in that table a text is set to the text box. It works fine but the problem is: as the text box is an html element it doesn't have viewstate and when a post back occures in the page its value disappeares.I tried a hidden field to keep its value.again there is another problem : I put this custom control in a usercontrol and put the usercontrol in a multiview and by clicking on a button this view is selected and by clicking another bu...

Custom Server Control Vs Web Parts, Any need for Custom Server Control
Hello I've just posted a similar question on why you need server controls when you can pre-compile usercontrols and redistribute them. http://forums.asp.net/p/1397433/3010100.aspx#3010100 I've seen lots of (usercontrol vs web part) but not much on web part vs custom server control. According to the MSDN site you can put web parts onto a normal asp.net page outside of a web part zone and they behave just like custom server controls. So, if you are creating a bunch of controls for redistribution to customer asp.net sites and/or SharePoint sites why don't you just create Web Par...

Dynamic custom control on custom control
What I'm trying to do is create a module for use within a larger page.  The page itself is an order form, which will have typical payment info (address, credit card, etc.), and the ability to select what you are paying for.  Our clients will have several options in how they want the page setup.  They can either have a single form, or they can have each module on it's own page.  They can also have all the selected items fire in a single transaction, or have a seperate transaction for each item selected.  And they can limit the total number of transactions a person can...

Web Custom Control within a Web Custom Control
I was wondering if this can be done and how. I've created a simple custom control that displays a header which is my first custom control. So I'm just a baby when it comes to this.. Within the header I currently have a property for breadcrumbs which is a string. What I would like to do is have the breadcrumb property  be a Link Button List. I did find a custom control of a Link Button List which is exactly what I wanted. My question is how can/do  I include this into my custom control? Can it done? How? Please help? I'm at a lose here.   Susan You should be able to do ...

Events and dynamically created controls (within a custom control)
I've created a custom control that displays a list of folders from a directory.  The user can click a folder (ImageButton) to drill-down and view the files within the folder.  I've developed the control by adding rows and cells to a <asp:Table>.  I create the controls within the cells (ImageButton and Labels) dynamically based on whether we want to see the folders or the files. Originally I was drawing the table depending on whether Folders or Files were desired but I realized that this will not work because on postback the target controls don't always exist...

Register Events on Control inside Custom Server Control
 I have some dynamically generated LinkButtons inside my custom server control. I never know how many there are going to end up being. I need to bind a 'Command' event to these. I understand that this nieeds to be done in the controls 'OnInit' event. I need to also add items to my server control dynamically in a pages codebehind, which will, in turn, dynamically create more linkbuttons. I'm having trouble keeping both these functionalities in one, as the OnInit event of the server control occurs before the page_Init event of my ASP.Net page.Here's the code of my ...

How to Render controls within an UpdatePanel in a Custom Server Control
Hi,Im writting a CompositeControl that contains a few UpdatePanels (TabContainer with an UpdatePanel on each TabPanel to make Tab control panels load "on-demand"). I want to control the renderring of the controls within the UpdatePanel's ContentTemplateContainer.How should I implement the render method of my CompositeControl?Should I use a custom UpdatePanel (inherit from UpdatePanel and override the RenderContents method)? is there a simpler solution? (because I need a different "render" for each tab panel....)Thanks Tal88 Hi, I want to control the renderring o...

Web resources about - Handling events from controls within custom controls - asp.net.custom-server-controls

Automobile handling - Wikipedia, the free encyclopedia
Automobile handling and vehicle handling are descriptions of the way wheeled vehicles perform transverse to their direction of motion, particularly ...

New Facebook SDK For IOS Adds Automatic Error Handling, Improved Login UI
... software-development kit for iOS is now available for download , with significant enhancements including a beta test of automatic error handling ...

Handling Disputes and Refunds
Handling Disputes and Refunds

Facebook Shares Stats on How Users are Handling the Latest Privacy Changes
Facebook’s traffic has yet to be affected by the aggressive privacy changes it made at the beginning of December, from what data we can see — ...

Handling five billion sessi
... into their mobile apps. Skip to main content Engineering Blog Have an account? Sign in Search form Search All Twitter Blogs &nbsp Handling five ...

Customer Service Handling
This group is for people in customer service profession facing the customer either in person or over phone.

Avocado Meal Planner - Meal planning, recipe handling and grocery shopping made easy on the App Store ...
Get Avocado Meal Planner - Meal planning, recipe handling and grocery shopping made easy on the App Store. See screenshots and ratings, and read ...

Vintage Ad #964: Students deserve Special Handling at Bob Jones University - Flickr - Photo Sharing!
I recently acquired a large number of Christian lifestyle magazines from the 60s and 70s. This ad features an institution that has tended to ...

How to Fly the P-47: Ground Handling, Take-Off, Normal Flight, Landing - 1943 - WDTVLIVE42 - YouTube
Demonstrates procedures in flying the P-47. Includes preflight and cockpit checks, warm-up, taxiing, cruising, banking, stalling, speeds for ...

34% Rate Obama’s Handling of Government Spending As Good or Excellent
Voters continue to question President Obama's handling of issues related to government spending and taxes. A new Rasmussen Reports national telephone ...

Resources last updated: 11/24/2015 7:17:47 AM