Serverside Template Control - Accessing Template Controls at Run Time

I've created a template control what I am running into difficults is during the Page_Load event on my web page I cannot access the child controls in the two possible templates.
What I would like to be able to do is set the value or make some changes to the control at runtime but I have not been successful in gaining code access to the control, for example the TEXTBOX1 control in the EditTemplate template.    

Does anyone know a good way to preform this task, let alone if I am even using the correct event

Example of HTML Render

 <aspSample:TextLabelControl ID="CustTest" runat="server">
<EditTemplate>
  
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditTemplate>
<ViewTemplate>
  
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ViewTemplate>
</aspSample:TextLabelControl>

My Test Control Code:
1    using System;
2    using System.ComponentModel;
3    using System.Web.UI;
4    using System.Web.UI.WebControls;
5    using System.Web.UI.Design;
6    
7    
8    
9    namespace Samples.AspNet.CS.Controls.TextLabelControl 
10   {
11       [Designer(typeof(TextLabelControlDesigner)),
12       ToolboxData("&lt;{0}:TextLabelControl runat=server></{0}:TextLabelControl>"),
13      ParseChildren(true)]
14       public sealed class TextLabelControl : WebControl, INamingContainer
15       {
16   
17           // Field for the templates
18   
19           private ITemplate editTemplate;
20           private ITemplate viewTemplate;
21           private Boolean actionControl;
22           private string valueControl;
23           
24   
25           public TextLabelControl()
26           {
27           }
28   
29   [PersistenceMode(PersistenceMode.InnerProperty), 
30   TemplateContainer(typeof(TemplateControl)), 
31   TemplateInstance(TemplateInstance.Single) ]
32   
33           public ITemplate EditTemplate
34           {
35   
36               get { return editTemplate; }
37               set { editTemplate = value; }
38   
39           }
40   
41   [PersistenceMode(PersistenceMode.InnerProperty), 
42   TemplateContainer(typeof(TemplateControl)), 
43   TemplateInstance(TemplateInstance.Single) ]
44   
45           public ITemplate ViewTemplate
46           {
47   
48               get { return viewTemplate; }
49               set { viewTemplate = value; }
50   
51           }
52   
53           public Boolean Edit
54           {
55               get { return actionControl; }
56               set { actionControl = value; }
57           }
58   
59           public string Value
60           {
61               get { return valueControl; }
62               set { valueControl = value; }
63           }
64   
65           protected override void CreateChildControls()
66           {
67   
68               this.Controls.Clear();
69   
70               //EnsureChildControls();
71   
72               ITemplate template;
73   
74               if (actionControl == true)
75               {
76                   template = editTemplate;
77               }
78               else
79               {
80                   template = viewTemplate;
81               }
82   
83               PlaceHolder pan = new PlaceHolder();
84               template.InstantiateIn(pan);
85               this.Controls.Add(pan);
86   
87               //base.CreateChildControls();
88           }
89   
90       }
91   
92   
93       public class TextLabelControlDesigner : ControlDesigner
94       {
95           TemplateGroupCollection col = null;
96   
97           public override void Initialize(IComponent component)
98           {
99               // Initialize the base
100              base.Initialize(component);
101              // Turn on template editing
102              SetViewFlags(ViewFlags.TemplateEditing, true);
103          }
104  
105          // Add instructions to the placeholder view of the control
106          public override string GetDesignTimeHtml()
107          {
108              return CreatePlaceHolderDesignTimeHtml("Click here and use " +
109                  "the task menu to edit the templates.");
110          }
111  
112  
113          public override TemplateGroupCollection TemplateGroups
114          {
115              get
116              {
117  
118                  if (col == null)
119                  {
120                      // Get the base collection
121                      col = base.TemplateGroups;
122  
123                      // Create variables
124                      TemplateGroup tempGroup;
125                      TemplateDefinition tempDef;
126                      TextLabelControl ctl;
127  
128                      // Get reference to the component as TemplateGroupsSample
129                      ctl = (TextLabelControl)Component;
130  
131                      // Create a TemplateGroup
132                      tempGroup = new TemplateGroup("Template Set A");
133  
134                      // Create a TemplateDefinition
135                      tempDef = new TemplateDefinition(this, "Template Edit",
136                          ctl, "EditTemplate", true);
137  
138                      // Add the TemplateDefinition to the TemplateGroup
139                      tempGroup.AddTemplateDefinition(tempDef);
140  
141                      // Create another TemplateDefinition
142                      tempDef = new TemplateDefinition(this, "Template View",
143                          ctl, "ViewTemplate", true);
144  
145                      // Add the TemplateDefinition to the TemplateGroup
146                      tempGroup.AddTemplateDefinition(tempDef);
147  
148                      // Add the TemplateGroup to the TemplateGroupCollection
149                      col.Add(tempGroup);
150  
151                  }
152  
153                  return col;
154              }
155          }
156  
157          // Do not allow direct resizing unless in TemplateMode
158          public override bool AllowResize
159          {
160              get
161              {
162                  if (this.InTemplateMode)
163                      return true;
164                  else
165                      return false;
166              }
167          }
168      }
169  
170  }
171  
 
0
bkthomson
9/21/2007 9:07:54 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

1 Replies
920 Views

Similar Articles

[PageSpeed] 24

Hi,

From the code you provided, the code works well. Actually, if you take a look at the custom server control you provided, you can find there’s a active template designed in that control, only if you set the Edit property to true, the EditTemplate will be the active template, otherwise, ViewTemplate is the active one.

So based on the control you provided, you can use it in two ways:
Suppose you have declared your custom server control on aspx page in the following way:

<cc1:TextLabelControl ID="TextLabelControl1" runat="server">
            <EditTemplate>
                    <asp:TextBox ID="textbox1" Text="abc" runat="server"></asp:TextBox>
            </EditTemplate>
            <ViewTemplate>
                    <asp:Label ID="Label" runat="server" Text="Hello"></asp:Label>
            </ViewTemplate>
        </cc1:TextLabelControl>

 Scenario 1: Set Edit property to false (or don’t set the Edit property), the ViewTemplate will actually take effect.

Label lb = this.TextLabelControl1.FindControl("Label") as Label;
TextBox tb = this.TextLabelControl1.FindControl("textbox1") as TextBox;

Response.Write(tb.Text); // Null exception occurs.
Response.Write(lb.Text); // Output: Hello

Scenario 2: Set Edit property to true, the EditTemplate will actually take effect.

this.TextLabelControl1.Edit = true;
Label lb = this.TextLabelControl1.FindControl("Label") as Label;
TextBox tb = this.TextLabelControl1.FindControl("textbox1") as TextBox;

Response.Write(tb.Text); // Output: abc
Response.Write(lb.Text); // Null exception occurs.

Thanks.


Michael Jin.
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Nai
9/25/2007 8:15:07 AM
Reply:

Similar Artilces:

Using a templated control inside a databound templated control
Hi,  We have a large number of pages that display contents in a simple header - content combination. To facilitate styling, we have created a custom control 'ContentArea' that exposes two template properties: HeaderTemplate and ContentTemplate. These allow a designer to define the layout for the header and content in the aspx file. In addition, two themable properties named HeaderCssClass and ContentCssClass allow the definition of a Css class for both texts. Like this, using theming, defining the style of our site contents becomes extremely simple. As an exampl...

How To Convert c#2005.net web template to vb2005.net Forms Template
I need  Convert c#2005.net web template to vb2005.net Forms Template   There are some free c# to vb converters out there which will allow you to upload a project and convert it to vb.   The programming models for windows forms and web projects are very different there is no way to convert a web to windows forms project.   http://www.carlosag.net/Tools/CodeTranslator/Default.aspx      Silverlight-helpVb TipsSpace Coast .Net User Group Hey Ajax-y, This tool really helps all programmers. I thought I would share this wit...

How to 'programmatically' add controls to the template of a Templated Server Control ?
Hi all,I am trying to build a Templated Server Control based on an example in MSDN here.  Everything worked ok.Now, as the next step, I would like to do the followings:1. Add new controls to the template programmatically. For example, adding a TextBox and a Button2. Persist these newly added controls 'and' their value between postback.  So, if users fill-in the above TextBox and click on the Button, I would like to persist the value that the user filled into the TextBox.3. Wire these controls' events. For example, I want to wire the OnClick event of the above Button.4. Have referen...

how do i ensure that a composite control support Web control Templates?
how do i ensure that a composite control support Web control Templates?...

Controlling web control instances on Web Form
I have created a composite control, extending functionality of the Hidden Control. However, I would like to prevent the user from adding this control to the page multiple times. I only want one instance of the control on the Web Form. What setting in my project to I adjust to enable this functionality? I can not find it in any of the books that I have referenced. Is this a setting or is this code that has to be added to the inheriting class. Looks like there is no standard apporach. But I'd consider using static field to count number of created objects and throw exception if second object ...

.NET Templated control design time support
Hi, I have a templated control, to which design time, I add nested controls to the template like so: <MYC:CollapsiblePanel id="CollapsiblePanel4" runat="server" HeaderText="bla bla" Collapsed="False"> <ItemTemplate> <asp:label id="Label1" text="Label1" Runat="server"></asp:label> <asp:label id="Label2" text="Label2" Runat="server"></asp:label> </ItemTemplate> </MYC:CollapsiblePanel> The thing is, if I edit the C...

Web User Control and templates at design time
Hi, I created a user control that when rendered, looks like this: The content area is a DIV and i'd like to customize this area at design time when i drag and drop the control onto a form.Like some other controls, i'd like to have here that option to click on "Edit Templates" and be able to drag and drop other controls inside this area.Is that possible? (by the way, i'm using VB.NET / VS 2005) Hi, Based on my experiences, you could create a custom control with the template. Here is the msdn tutorial article http://msdn2.microsoft.com/en-us/library/aa478964....

Why web form controls Disappear in run time?
Dear All I have facing a problem with Visual Studio .Net , I am using web form and I made a full screen design using the .NET controls, When I finished the design and run the *.ASPX Page I found that the all controls Disappear from the browser . Any idea about why the web form controls Disappear in run time? Although when I comeback again to the form design I found all control exist as I designed . Thanks for your help Note : I am using VS.NET 2002 with Framework 1.0 service pack 3 Wizard Perhaps that blank page is your default start up page. Rightclick your aspx in sol...

add controls to web form at run time
Dear all,  I have one question that may be familiar with some of you. As you know that in some job web site, if you are adding your job experiences in which the numbers are in the range. It can be severals. If in the web form we only have two sets of controls for entering job experiences information. How can we do if user have more than two? Can we add more sets of controls at run time for job experience information when user are clicking add job experiences button?  Do you have any sample codes? The controls can be dropdownlist, textboxes, labels or buttons!!!   Th...

add some controls to the Seperator Template in run time
Hi,I want to add some controls to the Seperator Template of a DataList in run time. How can I do that? Handle the ItemDataBounnd/RowDataBound and check for the seperator template. If it's that type of item/row then you have access to it, so add in the control there.-BrockDevelopMentorhttp://staff.develop.com/ballen...

Referencing a control in a Template control
I have a DetailsView in which one of the Fields is a TemplateField control, and this has an EditItemTemplate which contains a DropDownList. How do I reference that DropDownList from my code behind?  I tried DetailsView1.FindControl("xxx") but it didn't work. Thanks.  hc1   hc1: I tried DetailsView1.FindControl("xxx") but it didn't work.To reference a control that is placed in the EditItemTemplate of the detailsView, the DetailsView must be in Edit  Mode ( CurrentMode=Edit )so you need to check the detaildview mode before trying to access ...

how to call controls of web control form in coding of other forms?
hello everyone i have one problem i have created one webcontrol shoppingcart in which there are two labels one of qty and other of amt which are initially enable =falsenow on other page(aspx page) i have one txtbox of qty as txtqty i want tat as soon as user enters qty txtqty and clicks on add cart button it shd be display d value in lblqty of web control shopping cart make sure i m using datalist on aspx page so give me suggestions on tat basis and my coding is in vb. plz give ur suggestions as fast as possible. Neeti what do you mean by webcontrol.... it this user control or normal ...

How to find the ID of a web control tht sits inside a FormView Control Template?
I need advice how to find the ID of a control inside a template. Say a DropDownList inside the Insert template of a FormView When looking at the DropDownList in the Solution Explorer its ID is f. ex. DropDownList1 When looking up to the dropdownlist of controls on the page my DropDownList is : FormView1.InsertItemTemplate.InserItemTemplate.DropDownList1 But neither of these IDs can be used to reference the control in a code behind page What to do? You can't directly access controls nested inside of another control. You have to access them programmatically. This should work you will n...

Creating web form template & aligning controls
No question too simple, right? Question #1: How do you align all controls on a web form so that they will always be centered on the users browser, regardless of window size? I thought that would be an easy-enough question to find out on my own....but I am mistaken. I couldn't find the answer anywhere. Please don't tell me I have to insert them all in a html table ;-) Question #2: There has to be an easy way to display a .gif image to all pages of my application without having to add it manually. Can I create a template for all my webforms? Or do I have to create frames in one of the st...

Can't find a GridView inside a template of a custom templated web control
This is my first Templated Web Control I've written and I hope someone can help. I have three templates inside my web control and I'm trying to find a GridView inside one of them.  Naturally, it's throwing a null reference exception.  Here is the code for my user control:  1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Text; 5 using System.Web; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 9 namespace MyWebControls 10 { 11 [ToolboxData("&lt;{0}:Sec...

Web resources about - Serverside Template Control - Accessing Template Controls at Run Time - asp.net.web-forms

Ville Saarinen (@vsaarinen) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Open Directory - Computers: Internet: Cloud Computing
... information, standard documentation(s) or properly written guides (textual or video guide) on topics related to usage or guides for serverside ...

AOL Instant Messenger - Wikipedia, the free encyclopedia
7.5.12.6 / March 19, 2012 ; 4 months ago ( 2012-03-19 ) AOL Instant Messenger (abbreviated AIM ) is an instant messaging and presence computer ...

StartUp Jobs Asia - We Bring Great Talents to Great Startups!
Startup Hire, Startup Hiring, Startup Recruiting, Work in Startup in Singapore , Malaysia , Thailand - Easily search for hundreds of startup ...

Windows – reading the tea leaves
del.icio.us Tags: Windows7 , Microsoft , Windows , Beta Funny how when you say “reading tea leaves” – it means looking into the future. And yet, ...

Backend Techlead at DriveCarma ~ Authentic Jobs
... scalable backend systems but ready to hack web and mobile clients when required. Responsibilities: Define, implement, and support serverside ...

Disagreeing with Ken Arnold on Java Design, Kapor Vaporware and a Triple F List
... I've ... Java [and C#] Design Issues I recently found an interview with Ken Arnold , one of the original designers of CORBA, via The ServerSide ...

Airbnb Engineering - Home
We first introduced Rendr, our library for running Backbone.js apps seamlessly on both the client and the server, in a blog post a few months ...

JavaScript image deep ZOOM gallery PHP / ASP.NET visual configurator
Embeded example of JavaScript zoom gallery with a possibility to visually change some options such as gallery types, motions, positions, colors, ...

Serverside stylesheet switcher
... support isn't high enough to support the stylesheet switcher (e.g. jQuery isn't supported). You can program this page in whatever serverside ...

Resources last updated: 12/8/2015 1:16:44 AM