Web custom control does not maintain values of child controls

Hello everybody Smile

A few days now, I am struggling with a custom web control I am creating, which consists of 3 drop down lists (country/city/hotel).

Procedure is simple: On country change, I have to fill the cities with autopostback, and on city change I have to fill hotels again with auto postback. I tried many many methods and I am confused... The best I managed to make is keep the state of countries, and render it with the selected country, selected while filling cities with apporpriate data, however I cannot manage to do the same with the cities/hotels since sities does not keep selected value.

I relised that this is happening because after rebounding the data to countries, it fires the SelectedItemChange event, thus not firing the same event for cities, in order to fill hotels.

I know that it is practical to bound data only if not is PostBack, however, this control will be used in a page (among others), that PostBack is always true Confused

 Here is a dummy code:


1    Public Class CountryCityHotel
2    	Inherits WebControl
3    	Implements IPostBackEventHandler, INamingContainer
5    	Private buttonsCell As TableCell
6    	Private dataTable As Table = New Table()
7    	Private m_dataSet As STData
9    	Protected WithEvents countryDDL As DropDownList
10   	Protected WithEvents cityDDL As DropDownList
11   	Protected WithEvents hotelDDL As DropDownList
13   	Protected Overrides Sub CreateChildControls()
14   		CreateControls()
15   		CreateTables()
16   	End Sub
18   	Private Sub AddControls()
19   		With Me
20   			With .countryDDL
21   				If (Me.countryDDL Is Nothing) Then
22   					Me.countryDDL = New DropDownList
23   					.Enabled = True
24   					.ID = "CountryID"
25   					.AutoPostBack = True
26   					.CssClass = "fldData"
27   					.EnableViewState = True
28   					.Width = 230
29   					.ToolTip = "Please select the country you want to find hotels for."
30   					buttonsCell.Controls.Add(countryDDL)
31   				End If
32   			End With
34   			With .cityDDL
35   				If (Me.cityDDL Is Nothing) Then
36   					Me.cityDDL = New DropDownList
37   					.Enabled = True
38   					.ID = "CityID"
39   					.AutoPostBack = True
40   					.CssClass = "fldData"
41   					.EnableViewState = True
42   					.Width = 230
43   					.ToolTip = "Please select the city you want to find hotels for."
44   					buttonsCell.Controls.Add(cityDDL)
45   				End If
46   			End With
48   			With .hotelDDL
49   				If (Me.hotelDDL Is Nothing) Then
50   					Me.hotelDDL = New DropDownList
51   					.Enabled = True
52   					.ID = "HotelID"
53   					.AutoPostBack = False
54   					.CssClass = "fldData"
55   					.EnableViewState = True
56   					.Width = 230
57   					.ToolTip = "If you want a specific hotel, please select it from the list."
58   					buttonsCell.Controls.Add(hotelDDL)
59   				End If
60   			End With
61   		End With
62   	End Sub
64   	Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
65   		AddControls()
66   		MyBase.Render(output)
67   	End Sub
69   	Private Sub CreateControls()
70   		Me.countryDDL = New DropDownList
71   		With Me.countryDDL
72   			.Enabled = True
73   			.ID = "CountryID"
74   			.AutoPostBack = True
75   			.CssClass = "fldData"
76   			.EnableViewState = True
77   			.Width = 230
78   			.ToolTip = "Please select the country you want to find hotels for."
79   		End With
81   		Me.cityDDL = New DropDownList
82   		With Me.cityDDL
83   			.Enabled = False
84   			.ID = "CityID"
85   			.AutoPostBack = True
86   			.CssClass = "fldData"
87   			.EnableViewState = True
88   			.Width = 230
89   			.ToolTip = "Please select the city you want to find hotels for."
90   		End With
92   		Me.hotelDDL = New DropDownList
93   		With Me.hotelDDL
94   			.Enabled = False
95   			.ID = "HotelID"
96   			.AutoPostBack = False
97   			.CssClass = "fldData"
98   			.EnableViewState = True
99   			.Width = 230
100  			.ToolTip = "If you want a specific hotel, please select it from the list."
101  		End With
102  	End Sub
104  	Private Sub CreateTables()
105  		Dim tbl2 As Table = New Table()
106  		With tbl2
107  			.Width = 550
108  			.BorderWidth = 0
109  			.CellSpacing = 0
110  			.CellPadding = 1
111  			.HorizontalAlign = HorizontalAlign.Center
112  		End With
113  		Dim row2 As TableRow = New TableRow()
114  		buttonsCell = New TableCell()
115  		With buttonsCell
116  			.ID = "cellHolder"
117  			.HorizontalAlign = HorizontalAlign.Center
118  			.CssClass = "Data"
119  			.Controls.Add(New LiteralControl("<br/>"))
120  			.Controls.Add(countryDDL)
121  			.Controls.Add(New LiteralControl("<br/>"))
122  			.Controls.Add(cityDDL)
123  			.Controls.Add(New LiteralControl("<br/>"))
124  			.Controls.Add(hotelDDL)
125  			.Controls.Add(New LiteralControl("<br/>"))
126  		End With
128  		getListsData("country")
129  		getListsData("origin")
131  		row2.Controls.Add(buttonsCell)
132  		tbl2.Controls.Add(row2)
133  		.Controls.Add(tbl2)
134  	End Sub
136  	Private Sub getListsData
137  		'bounds the data
138  	End Sub
140  	Private Sub countryDDL_Changed(ByVal sender As Object, ByVal e As EventArgs) Handles countryDDL.SelectedIndexChanged
141  		getListsData("city")
142  		cityDDL.Enabled = True
143  	End Sub
145  	Private Sub cityDDL_Changed(ByVal sender As Object, ByVal e As EventArgs) Handles cityDDL.SelectedIndexChanged
146  		getListsData("hotel")
147  		hotelDDL.Enabled = True
148  	End Sub
149  End Class
"I know one thing, I know nothing" - Socrates 469bC - 399bC
2/6/2008 2:20:31 PM
asp.net.state-management 8807 articles. 0 followers. Follow

8 Replies

Similar Articles

[PageSpeed] 39

After hours of debugging and testing and trying, I came with the conclusion that the City DDL, does not maintain its value. On every event of the page (init, load, etc) either it is empty, or its value is 0...

 What am I doing wrong? Confused

"I know one thing, I know nothing" - Socrates 469bC - 399bC
2/7/2008 10:36:56 AM

The logic that happens in AddControls method happens at render stage which is too late for state to be kept and such (viewstate is saved after PreRender, postback data loaded till Load stage of the Page). Try moving that logic earlier, or combining into the one beinf run when CreateChildControls is called - so that your controls would be there when page lifecycle deals with state (postback data or viewstate)


Teemu Keiski
Finland, EU
2/9/2008 11:49:42 AM

 joteke thanks for the answer. However, I think I tried that with no effort... On the other hand, since the control does not have selectedValue at any stage of the page creation, what difference would it make...? Huh?

"I know one thing, I know nothing" - Socrates 469bC - 399bC
2/11/2008 9:08:33 AM

I'm not sure that's true. After CreateChildControls is called (say in the page prerender), you should have access to the selected value of a drop down. Just make sure where ever you try to get that value you first call EnsureChildControls() and that the control has viewstate enabled.

2/14/2008 6:43:20 PM

I tried with EnableViewState true, however it did not make any difference. Do I have to call EnsureChildControls() ? There are 4 identical controls in this page. 1 & 4 maintain their values, without any actions. Why 2 & 3 don't? 

"I know one thing, I know nothing" - Socrates 469bC - 399bC
2/15/2008 8:54:58 AM

EnableViewState is true by default and it impacts on ViewState persistence - when it happens . EnsureChildCOntrols would be called in order to ensure controls are created (this is by adding the logic to create controls to CreateChildControls, EnsureChildControls checksd a flag to see if CreateChildControls is called and if not, calls it, and sets the flag)

Point is that if AddControls is called at Render, according to the code you posted, so controls get added to Controls collection at that time. And that is too late basically for everything when you're using composite controls - postback data is loaded before render (means that control selections won't be kept), viewstate is saved before Render - means that you'd need to databind on every request.  

Instead if the code relies on databinding, you should a) instantiate the controls in CreateChildControls and add to Controls collection and maybe b) override DataBind method and databind the controls (instantiated in CreateChildControls) there...this would mean that the logic using your control would need to call DataBind(). Anyways, do you implement databinding this way is secondary...point is that a control should create it's direct, preknown, child controls in CreateChildControls

And seems you now have duplicate code to create the controls? By triggering their creation in CreateChildControls, you don't need anything else thatn to call ensureChildControls, say ion OnLoad, and the controls are always there (although EnsureChildCOntrols should be automatically called at PreRender stage)

So, give me a two or three samples of the every type of real data coming to ddls (list if countries etc), I'll post a working sample with them.


Teemu Keiski
Finland, EU
2/15/2008 5:42:30 PM

I'm not sure why you are recreating the controls in  Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter). You shouldn't have to do that. Just include the EnsureChildControls() call before you call RenderChildren in that method should do it.

I've been building a bunch of composite controls at work, so I can share my experience. I create the controls inside of the Create Child Controls and then bind the drop down lists in the PreRender event inside of not page.ispostback. Then, in the slected index change event of the control that you change the value, you should have access to the ddl.selecteditem.value since the viewstate has now been loaded. You will then need to rebind the drop down lists that are dependant on this new value. Since I havean object that gets passing in the constructor, I update the object with all the values from viewstate before rebinding. Not sure if this is the best way to do it, but it's been working for me. 

Since you don't include any databinding code, the problem might be in there. Did you step through and check that the right values are being passed in?

2/15/2008 7:57:05 PM

Since your last answer, I made lots of controls, and following your advise, every single one, works fine. Except... the one above. I left it aside, in order to clear my mind since I had many other things to do, and now the time has come to complete it.

However, I removed the code from PreRender event, and also removed completely the AddControls sub. The problem I am experiencing is, that, since I cannot control the Page.IsPostback (I always have a post back event, even the 1st time visiting), I have to bind the data to Countries, every time in CreateChildControls. After that, it fires the SelectedIndexChanged event, thus NOT firing that event for the Cities dropdownlist.

How can I control, not to fire the event? I tried to remove the handler before the .DataBound() command, however it did not work. 


 @adyle: I tried to bind the data on PreRender, however it also looses the Country then.

"I know one thing, I know nothing" - Socrates 469bC - 399bC
2/26/2008 11:01:00 AM

Similar Artilces:

how to maintain the view state of child controls of custom control.......
Hi,       I am using asp.net and c#.net and creating the custom control ......I am creating the every part of the control with HtmlTextWriter like......private bool CreateFirstColumnHeader(HtmlTextWriter renderer) {int lf = 0; int tp = ControlPanelHeight + 1; //Create the container renderer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, HeaderBGcolor); //renderer.AddStyleAttribute(HtmlTextWriterStyle.Filter, "progid:DXImageTransform.Microsoft.Gradient(GradientType=1, StartColorStr='#F0F8FF', EndColorStr='#B0C4DE')");ren...

Passing values from a parent web control to child web control
I have a parent control which called CONTROL1 and a child control witch called CONTROL2 I would link to pass a value from the parent control to the child control. In the parent control(CONTROL1) I have the following Event Handler . private void btn_Handler(object sender, EventArgs e) { …      if (Page.IsPostBack) {              // Send the officer names to the child controls.             if(m_nameList.SelectedItem.Text != "")     ...

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

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

Custom web control and child control events
I generate a LinkButtons in a CreateChildControls() method of a custom web control and I want to catch click events of these LinkButtons in this custom web control class (in some method). Is it possible? Martin public class ExampleCompositeControl { public override ControlCollection Controls { get { EnsureChildControls(); return base.Controls; } } protected override void CreateChildControls() { this.Controls.Clear(); myLink = new LinkButton(); myLink.Click += new EventHandler( myLink_Click ); this.Controls.Add( myLink ); ...

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

Use property value in custom control child control
Hello, I am creating a custom control and I have the following property:   <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property Text() As String     Get       Dim s As String = CStr(ViewState("Text"))       If s Is Nothing Then         Return String.Empty       Else         Return s       End If     End Get     Set(ByVal Value As String)       ViewState("Tex...

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

User Control VB.Net x Web Custom Control
I was thinking in create a user control in VB.Net, and use it in a Asp.Net as possible? So I thought about it is gonna be better than make a Web Custom Control, so i thought again, nope... But i need to know better because a don't have a progress bar in asp.net for example.... Could Somebody tell me about??? in a reallity i know the asnwer but i would like to explain by myself... Thank's Antonio...

Custom Web Control w/ Child Composite Controls
 I'm trying to create a custom web control with child controls.   I would like to be able to use the child controls stand alone or within the parent control.  Here is the declarative markup: As you can see, the validation fails, though it compiles successfully.  My code (simplified) is below.  Any insight would be appreciated. 1 'Control Builder 2 Public Class FormControlBuilder : Inherits ControlBuilder 3 Public Overrides Function GetChildControlType(ByVal tagName As String, ByVal attributes As IDictionary) As Type 4...

I have a problem with dynamically loaded User Controls maintaining their child controls values
I have a Page that has a list box on it.  That list box shows reports.  When a report is selected it loads a user control dynamically.  On the page load of the control it loads the report object and sets the properties on the control (ie the selected index of a drop down list).  The problem is when I click on another item that loads the same user control but a different report.  It loads the selected index for my drop down box correctly in page load but when it gets to OnPreRender the Selected Index I specifically set in Page Load is 0. However it will work if I...

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

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

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

Web resources about - Web custom control does not maintain values of child controls - asp.net.state-management

How Facebook App Developers Can Maintain Momentum After The Holidays
Facebook reminded application developers that the end of the holiday season does not mean their efforts to attract more users must end, as well, ...

DoD maintains BRAC fight, despite opposition from Congress - FederalNewsRadio.com
Amid nearly unanimous congressional opposition, the Defense Department says it needs to stop operating military facilities it no longer wants ...

Iraq's clergy strive to maintain legacy amid rise of Shia militias
In Iraq, the most prominent Shia religious leader takes positions that minimise the risk of sectarian violence.

Family asks court to demand killer driver maintain loved one’s shrine at crash site - AdelaideNow Search ...
GRIEVING family have demanded a driver who struck down and killed a man be forced to maintain his shrine amid emotional scenes as he left court ...

Socceroos will maintain the rage in Asian Cup
Socceroos coach Ange Postecoglou reinforced his commitment to his aggressive game plan ahead of the team's final Asian Cup group match on Saturday. ...

To have and to hold: How five huge business families maintain their wealth
Some of the world's most prosperous businesses have been closely held by family members for generations.

Earl breaks silence to maintain innocence
Canberra winger Sandor Earl has maintained his innocence following allegations of peptide use, but admits he expects to be summoned for an interview ...

Apple iPad maintains strong Web traffic lead lead over Samsung Galaxy Tabs
Samsung is second to Apple in tablet sales and coming on strong, though Samsung Galaxy Tab users remain well behind iPad users in how much they ...

Socceroos World Cup qualifiers: Ange Postecoglou maintains attacking mindset for Bangladesh - DailyTelegraph ...
THE critics, says Ange Postecoglou, are “missing the point”. It’s not that playing attacking football poses a risk to the Socceroos’ hopes of ...

Resources last updated: 11/23/2015 11:06:36 AM