Custom Web Control inside another Custom Web Control

Hi

I created a custom web control (CusWebNew) that displays some textboxes by adding them to the ControlCollection of the webcontrol. I also created a custom webcontrol (CustWebButton) that inherts from Button control, and overrided the OnClick function.

When I use CustWebButton on a regular web form, it seems to function correctly.

However, when I added to be part of the ControlCollection of CustWebNew, it stops to work.

 

Any ideas why?

Thanks

0
m1net
3/5/2007 6:59:47 PM
asp.net.custom-server-controls 3498 articles. 0 followers. Follow

10 Replies
1197 Views

Similar Articles

[PageSpeed] 52

Hey,

What do you mean by stops to work?  Explain what you are trying to do with it and what it doesn't do.


Brian

"Trust in the Lord and do what is good; dwell in the land and live securely. Take delight in the Lord, and He will give you your heart's desires" (Psalm 37: 3-4).
0
bmains
3/5/2007 7:50:45 PM

I will try.

 I have a web form solution where I have my default.aspx

 

I created a Web Control Library project within my solution, this is CustWebNew. it has the following code:

     protected override void OnPreRender(EventArgs e)
        {
            TextBox fieldTextBox = new TextBox();
            fieldTextBox.ID = "TXTBOX";
            fieldTextBox.Text = "some text goes here";
            this.Controls.Add(fieldTextBox);
            base.OnPreRender(e);
        }

 

I added another Web Control Library, this is CustWebButton. To test it, I overrided the onclick method to change the displayed text from "preClick" to "postClick".

I drag & drop the CustWebButton to the main solutoin: default.aspx

Run, and press button - works, the displayed text changed.

I removed the CustWebButton from default.aspx.

 

I went to my CustWebNew project, added a reference to CustWebButton dll, then added the following lines to code above

     protected override void OnPreRender(EventArgs e)
        {

            CustWebButton newButton = new CustWebButton;
            TextBox fieldTextBox = new TextBox();
            fieldTextBox.ID = "TXTBOX";
            fieldTextBox.Text = "some text goes here";
            this.Controls.Add(fieldTextBox);

           this.Controls.Add(newButton);
            base.OnPreRender(e);
        }

I then drag and drop CustWebNew to my default.aspx; both textbox & button appear now on the screen, but pressing the button does not change the displayed text of the button.

 

I hope I explained clearly....

Thank You

0
m1net
3/5/2007 8:57:29 PM

Hey,

Yes, sure, but you don't tap into the click event...  You can do that by adding (after you add the button to the controls collection):

newButton.Click += new EventHandler(newButton_Click);

And adding:

void newButton_Click(object sender, EventArgs e)
{
    TextBox box = this.FindControl("TXTBOX") as TextBox;
    if (box != null)
        box.Text = "post click";
}

Also, I wouldn't recommend using OnPreRender to add controls, but would use create a class from the CompositeControl class, and override CreateChildControls instead, and create your class there.


Brian

"Trust in the Lord and do what is good; dwell in the land and live securely. Take delight in the Lord, and He will give you your heart's desires" (Psalm 37: 3-4).
0
bmains
3/6/2007 3:27:58 PM
BMains is right... but also note that adding the eventhandler at prerender is too late (which is why he said to move the location of this code in general) for a click event.  Page_Load() is pretty much the last stop for the event train.  If you want to get onboard, you need to do it before then.
Does your team use the VSIP toolkit or maybe have the bulk of your app factored down to patterns and generators? Do you need in-house controls that will make your current vendors blush? If so, we need to talk.
0
Jonathan
3/6/2007 7:26:04 PM

Thanks for the reply bmains

Before I go and create a CompositeControl class, I wanted to make sure that the first solution acutally works.

I tried it, even with a regulare Button and the event doesn't fire...

 

Am I missing something?

0
m1net
3/6/2007 10:53:09 PM

Hey,

Yes, move the controls to the CreateChildControls collection, because as it was said above, OnPreRender is too late to receive the focus for the event handling (click occurs before OnPreRender).  So, if you move everything to CreateChildControls, it should work.  Your solution will work, so you don't have to worry about spending time on something that won't.  Just, you have to move it to CreateChildControls.


Brian

"Trust in the Lord and do what is good; dwell in the land and live securely. Take delight in the Lord, and He will give you your heart's desires" (Psalm 37: 3-4).
0
bmains
3/7/2007 12:28:54 PM

:( it is not working; this is my code - am I doing correctly?:

namespace HimmaAdvancedForm
{   
    [DefaultProperty("Text")]
    [ToolboxData("&lt;{0}:HimmaAdvancedForm runat=server></{0}:HimmaAdvancedForm>")]
    public class HimmaAdvancedForm : WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        [Bindable(true)]
        [Category("HimmaData")]
        [DefaultValue("")]
        [Localizable(true)]
        public string EntityName
        {
            get
            {
                String s = (String)ViewState["EntityName"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["EntityName"] = value;
            }
        }

        [Bindable(true)]
        [Category("HimmaData")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Operation
        {
            get
            {
                String s = (String)ViewState["Operation"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Operation"] = value;
            }
        }

        [Bindable(true)]
        [Category("HimmaData")]
        [DefaultValue("")]
        [Localizable(true)]
        public string OperationSQL
        {
            get
            {
                String s = (String)ViewState["OperationSQL"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["OperationSQL"] = value;
            }
        }        

        public void btnNew_Click(object sender, EventArgs e)
        {
            string x;
            x = "1";
        }
    
        protected override void  CreateChildControls()
        {
               base.CreateChildControls();
              // this.Controls.Add(buildWebTable());
               Button btnNew = new Button();
               btnNew.ID = "NEW_RECORD2";
               btnNew.Text = "2" + HttpContext.GetGlobalResourceObject("Resource", "NEW").ToString();
               this.Controls.Add(btnNew);
               btnNew.Click += new EventHandler(btnNew_Click);
        }
    }
}
 
0
m1net
3/7/2007 3:42:24 PM

Got it :)

I was not implementing INamingContainer

 Once I did that, it began to work...

Thank you :D

0
m1net
3/7/2007 3:56:17 PM

Hey,

May I suggest a change, from this:

Button btnNew = new Button();
btnNew.ID = "NEW_RECORD2";
btnNew.Text = "2" + HttpContext.GetGlobalResourceObject("Resource", "NEW").ToString();
this.Controls.Add(btnNew);

to this:

Button btnNew = new Button();
this.Controls.Add(btnNew);
btnNew.ID = "NEW_RECORD2";
btnNew.Text = "2" + HttpContext.GetGlobalResourceObject("Resource", "NEW").ToString();

It may not seem like a lot, but I read on some blogs that you should add the control right after you create it so viewstate can work properly.


Brian

"Trust in the Lord and do what is good; dwell in the land and live securely. Take delight in the Lord, and He will give you your heart's desires" (Psalm 37: 3-4).
0
bmains
3/7/2007 4:48:27 PM

I will do that, thank you :)

 

0
m1net
3/8/2007 1:59:21 PM
Reply:

Similar Artilces:

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 ...

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...

Server Web User Control or Web Custom Control
Ok, I made a DataGrid I like, stuck it in a Web Control Lib, and then to my toolbar. Now I want to take my nice little control and add it to a greater control, maybe place some buttons around it etc. I could always inherit from it in a new custom control and dynamically add the buttons, but I thought about using a Web User Control. I thought I could easily create a Web User Control, drop on my grid and the buttons on a form, and expose some properties and events, but once I got into it, I got a feeling that this isn't what a Web User Control is for. When designing a control li...

Custom User Controls v. Custom Web Controls
Hi! Is it better for me to begin coding my controls instead of just designing them? What would the benefits be? I meen, i seem to be able to get all i need from just putting stuff together on an ASCX file but i'm obviously missing a huge concept here... please explain! Hi, creating user controls is indeed easier than creating custom server controls because you can simply drag & drop other controls on the form, easily add events to it, ... Custom controls however are better when you want to reuse them in several other projects. I like to create custom controls for small, reusable com...

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...

Reusing custom web control in the same web control
Hello, I'm newbie in web development and of course asp.net. I am actually trying to build my first page and I'd like to know if it is possible to make a custom webcontrol that will contain itself. Let's say I want to draw a folder hierarchy in treeview-like structure. I thought I could make a control that will display a folder and if this folder contains subfolders then for each the control will include itself. Is this even possible? What would you suggest me to do to? Thanks in advance. TomTom Hagen http://thagen.dteam.info If the control can have child controls, then I s...

Creating Custom Controls With Custom Controls Inside Of Them
Hello, I am trying to create a custom control for creating tabs. The idea is that our designer can just use the control tags to generate the tabs.  The problem that I am running into is that I want to be able to have a custom control that allows any number of child custom controls. So there would be a TabContainer Control, and within that there would be any number of tabs.  The idea is similar to how an asp:DropDown list can have any number of ListItems within them.  Here is my code, any help is appreciated. 1 <!-- TAB CONTAINER -->2 <%@ Control Language=&...

Custom controls called from inside other custom controls???
I'm fairly new to writing controls in ASP.NET so, forgive the I am trying to create a base page class which will call 3 custom controls. This base page class will span across multiple projects hence the reason I am not creating user controls. These 3 custom controls are: 1. TopNav-uses render method to display an HTML table with graphics for top navigation. 2. ImagePairs-uses prerender method to add javascript code to manage what graphic is displayed in TopNav onMouseOver and onMouseOut 3. MgrHeader-uses render method to display an HTML table with s...

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....

What is the difference between a Web User Control and a Web Custom Control
Hi ,please could you answer for the following question with example. i know wht they are. but i want to know hw they are existing in web pages with simple example. What is the difference between a Web User Control and a Web Custom Control?  Thanks in AdvanceDilip    Check this out .... hope these might help you out... http://support.microsoft.com/kb/893667http://msdn2.microsoft.com/en-us/library/aa651710(VS.71).aspx itsUrDAY  Hi, See the following URLs: https://msdn2.microsoft.com/en-us/library/fb3w5b53(VS.71).aspx(Introduction to Web User Contr...

Use Web Custom control or Web User control?
Friends,  I have a generic aspx page and its functions which is used in many .NET web application. The generic page contains a HTML Div control, server drop down list, server buttons, server textbox and it have different server and client functions to do its tasks for calling aspx pages in web applications. My problem is I do not know whether I should make that generic page as a web user control (but this is tedious because all other application folders must store frontpage aspx and code behind files of the generic page) or as a web custom control (This seems to be good beca...

Add .Net Control to Web Custom Control
 I want to add .NET Control (like: TextBox, Button...) to Web Custom Control.How i can do it? Alphavn That's called a composite control -- "Mark As Answer" if my reply helped you -- Hello Guys What gunteman said, that is one approach and in most cases the right one.But its also possible to add child controls to a Control thats inherit from WebControl itself. Be sure to implement INamingContainer to that inherited Control too, thats the important point of that approach.--Microsoft MVP - Visual Developer ASP / ASP.NET- http://www.aspnetzone.de/blogs/peterbuch...

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...

error parsing web control inside custom control
I have the following: ------------------------------------------------ <!-- page.aspx --> <%@ Page Language="C#" %> <%@ Register TagPrefix="MyTag" tagname="PageTemplate" Src="./Includes/DefaultPageTemplate.ascx" %> <script runat="server"> protected void Page_Load(Object Src, EventArgs E) { //!!!!!!!!!!!!!!!!!!!!!!!! label1.Text = "asdf"; //! the line above causes an error !!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!! } </script> <MyTag:PageTemp...

Web resources about - Custom Web Control inside another Custom Web Control - asp.net.custom-server-controls

Control - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Labor senator Sam Dastyari claims 10 companies have taken control of Australian politics
Labor senator Sam Dastyari has warned there is something &quot;fundamentally wrong and rotten&quot; with Australia's entire political system, ...

Who Controls the User Experience? AMD’s Carrizo Thoroughly Tested
In Q2 of 2015, AMD officially launched Carrizo, their new APU aimed at mobile devices such as laptops and portable all-in-ones that normally ...

Continental Automotive recalls 5 million airbag control units
Filed under: Recalls , Chrysler , Fiat , Honda , Mercedes-Benz , Safety , Crossover , Minivan/Van , Sedan Only 580,000 Continental airbag-equipped ...

Zika Control Demands Anti-Mosquito Measures, Officials Say
Governments and residents of areas where Zika virus is spreading should redouble their efforts to limit exposure to mosquitoes that carry the ...

Study: Texas birth control fell after Planned Parenthood cut
Fewer women obtained long-acting birth control, births increased in poor families after state dropped Planned Parenthood from health program ...

Box helps businesses better control encryption of cloud data
Box has made it easier for its customers to control how stored data is encrypted with an update announced Thursday . The company announced a ...

Is Cosmo For Population Control?
Complains about increase in birth rate in Texas counties

Study finds Texas birth control use fell after GOP lawmakers hacked Planned Parenthood funding
... lo and behold, an independent study by the New England Journal of Medicine has found that resulted in fewer women using long-acting birth control. ...

Khloe Kardashian Says Kourtney Kept Her From 'Spiraling' Out of Control, Wants Rob to Be 'Happy'
The 'Kocktails With Khloe' host shared a touching post to her website, recalling how her sister saved her from a destructive path.

Resources last updated: 2/5/2016 5:07:10 PM