Persisting data in a web user control, which contains a list of other web user controls.

 Hi All,

 I have a control I've created, which can have a number of child controls - also user controls - stored as an ArrayList, which can be added wither a design time or programmatically.

My problem is when I add to the list programmatically, it doesn't persist them. So if I add 3 child controls in step 1 of a wizard, with the aim that those three will be visible inside the parent in step 3, what happens is that the parent has no child controls and the item count is 0.

Can anyone help? Thanks in advance.

Code:

Parent Control Markup:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Beneficiaries.ascx.cs" Inherits="Beneficiaries" %>
<%@ Register TagPrefix="gm" TagName="beneficiaryInput" src="~/beneficiaryInput.ascx" %>

<div runat="server" id="container">
</div>

 Parent Control Code:

1    using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.ComponentModel;
5 using System.ComponentModel.Design;
6 using System.Drawing.Design;
7 using System.Text;
8 using System.Web;
9 using System.Web.UI;
10 using System.Web.UI.WebControls;
11
12 [DefaultEvent("SelectedIndexChanged"),
13 Designer("System.Web.UI.Design.WebControls.ListControlDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
14 ParseChildren(true, "Items"), ControlValueProperty("SelectedValue"),
15 DataBindingHandler("System.Web.UI.Design.WebControls.ListControlDataBindingHandler, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
16 public partial class Beneficiaries : System.Web.UI.UserControl{
17
18 private ArrayList _Beneficiaries;
19
20 protected void Page_Load(object sender, EventArgs e) {
21
22 }
23
24 [DefaultValue((string)null), MergableProperty(false),
25 PersistenceMode(PersistenceMode.InnerDefaultProperty),
26 Editor("System.Web.UI.Design.WebControls.ListItemsCollectionEditor,System.Design, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
27 typeof(UITypeEditor))]
28 public virtual ArrayList Items {
29 get {
30 if (this._Beneficiaries == null) {
31 this._Beneficiaries = new ArrayList();
32 }
33 return _Beneficiaries;
34 }
35 }
36
37 protected override void CreateChildControls() {
38 if (this._Beneficiaries == null) {
39 this._Beneficiaries = new ArrayList();
40 }
41 foreach (object item in _Beneficiaries) {
42 container.Controls.Add((beneficiaryInput)item);
43 }
44 }
45
46 public void addBeneficiary() {
47 Control c = LoadControl("~/beneficiaryInput.ascx");
48
49 container.Controls.Add(c);
50 if (this._Beneficiaries == null) {
51 this._Beneficiaries = new ArrayList();
52 }
53 _Beneficiaries.Add(c);
54 }
55 }
  Child Control Markup: 
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="beneficiaryInput.ascx.cs" Inherits="beneficiaryInput" %>

<h3 runat="server" id="h3Title"></h3>
<label for="title">Title:</label> <asp:TextBox runat="server" ID="Title" CssClass="text" /> <span class="red">*</span><br />
<label for="forenames">Forename(s):</label> <asp:TextBox runat="server" ID="Forenames" CssClass="text" /> <span class="red">*</span><br />

<label for="surname">Surname:</label> <asp:TextBox runat="server" ID="Surname" CssClass="text" /> <span class="red">*</span><br /><br />
<label for="gender">Gender:</label>
<asp:RadioButton ID="female" GroupName="Gender" runat="server" /> Female    
<asp:RadioButton ID="male" GroupName="Gender" runat="server" /> Male
<br /><br />
<label for="receive">To receive:</label> <asp:TextBox runat="server" ID="receive" CssClass="text" /> <a class="boxhelppopup-0"><img src="images/help-icon.gif" width="19" height="19" alt="" /></a><br /><br /><br />

<label for="postCode">Post Code:</label> <input type="text" id="txtPostcodeLookup" class="text" maxlength="12" runat="server" /> <span class="red">*</span> <a href="#this" title="Find My Address"><img runat="server" id="addressFinder" src="images/buttons/find-my-address.gif" width="136" height="29" alt="Find My Address" style="vertical-align:middle;" /></a><br /><br />

<div runat="server" id="divAddressList" style="display:none;">
<label for="postCode">Select Address:</label>
<div id="divInnerAddressList"></div>
</div>

<div runat="server" id="divAddressDetails" style="display:none;">
<label for="houseNumber">House No/Name:</label> <asp:TextBox runat="server" ID="houseNumber" CssClass="text" /> <span class="red">*</span><br />

<label for="postCode">Post Code:</label> <asp:TextBox runat="server" ID="postCode" CssClass="text" /> <span class="red">*</span><br /><br />

<label for="address">Address:</label> <asp:TextBox runat="server" ID="address" CssClass="text" /><br />
<label for="address2">Address2:</label> <asp:TextBox runat="server" ID="address2" CssClass="text" /><br />
<label for="town">Town:</label> <asp:TextBox runat="server" ID="town" CssClass="text" /> <span class="red">*</span><br />

<label for="country">Country:</label> <asp:TextBox runat="server" ID="country" CssClass="text" /><br /><br /><br />
</div>
<asp:CheckBox runat="server" ID="isActive" OnCheckedChanged="isActive_OnCheckChange" Visible="false" />
 Child Control Code: 
1    using System;
2 using System.Collections.Generic;
3 using System.Web;
4 using System.Web.UI;
5 using System.Web.UI.WebControls;
6
7 public partial class beneficiaryInput : System.Web.UI.UserControl {
8
9 protected void Page_Init() {
10 //addressFinder.Attributes.Add("onclick", "addressFinder('" + this.ClientID + "')");
11 }
12
13 protected void Page_Load(object sender, EventArgs e) {
14
15 }
16
17 protected void isActive_OnCheckChange(object sender, EventArgs e) {
18 this.Visible = ((CheckBox)sender).Checked;
19 }
20
21 public bool active {
22 get {
23 return isActive.Checked;
24 }
25 set {
26 isActive.Checked = value;
27 this.Visible = value;
28 }
29 }
30
31 public string headerText {
32 get {
33 return h3Title.InnerText;
34 }
35 set {
36 h3Title.InnerText = value;
37 }
38 }
39
40 public string beneficiaryTitle {
41 get {
42 return Title.Text;
43 }
44 set {
45 Title.Text = value;
46 }
47 }
48
49 public string beneficiaryForenames {
50 get {
51 return Forenames.Text;
52 }
53 set {
54 Forenames.Text = value;
55 }
56 }
57
58 public string beneficiarySurname {
59 get {
60 return Surname.Text;
61 }
62 set {
63 Surname.Text = value;
64 }
65 }
66
67 public string beneficiaryGender {
68 get {
69 if (male.Checked) {
70 return "M";
71 }
72 if (female.Checked) {
73 return "F";
74 }
75 return "";
76 }
77 set {
78 if (value.ToLower() == "m") {
79 female.Checked = false;
80 male.Checked=true;
81 }
82 if (value.ToLower() == "f") {
83 male.Checked = false;
84 female.Checked=true;
85 }
86 }
87 }
88
89 public string beneficiaryPercentage {
90 get {
91 return receive.Text;
92 }
93 set {
94 receive.Text = value;
95 }
96 }
97
98 public string beneficiaryAddress1{
99 get{
100 return address.Text;
101 }
102 set{
103 address.Text=value;
104 }
105 }
106
107 public string beneficiaryAddress2{
108 get{
109 return address2.Text;
110 }
111 set{
112 address2.Text = value;
113 }
114 }
115
116 public string beneficiaryTown{
117 get{
118 return town.Text;
119 }
120 set{
121 town.Text = value;
122 }
123 }
124
125 public string beneficiaryCountry{
126 get{
127 return country.Text;
128 }
129 set{
130 country.Text = value;
131 }
132 }
133
134 public string beneficiaryPostcode{
135 get{
136 return postCode.Text;
137 }
138 set{
139 postCode.Text = value;
140 }
141 }
142 }
143
 
0
ManchesterCodeMonkey
11/23/2008 6:10:29 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

5 Replies
1453 Views

Similar Articles

[PageSpeed] 2

dynamically added controls need to be recreated and readded to the page on each and every postback - by page_load at the latest.

give this a read: http://forums.asp.net/t/1186195.aspx


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
11/23/2008 6:42:18 PM

 Cheers for that, however, shouldn't the contents of the ArrayList in the parent User Control persist the items added across postbacks?

 That way I can loop through ArrayList on Page_Load on the parent User Control, adding the Child User Controls.

 However, if I do a testControl.addBeneficiary(), then on the next postback output testControl.Items.Count it returns a 0.

Any suggestions as to why the ArrayList isn't persisting?

Thanks in advance

0
ManchesterCodeMonkey
11/23/2008 6:59:09 PM

No page variables will survive across a postback unless you take steps to persist them.  on a postback, a brand new page instance is created and it has no knowledge of what wah done in the previous page instance.  this is the nature of the web - it is stateless.  If you want values to survive postbacks, you need to persist those values somewhere such as ViewState, Session, Cookies, Database.

http://wiki.asp.net/page.aspx/30/state-management/


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
11/23/2008 7:05:44 PM

 I appreciate that, however surely the whole point of the viewstate is to provide a framework that does that for you?

With dynamically loaded controls I would expect to have to add their state to the viewstate via code, but with those those added at design time I would expect to work in the same way as another asp tag.

With a textbox, if I set it's text attribute to 'fred' via code at step 1, at step 3 it is still 'fred' - imo an attribute set on a user control should operate in the same fashion. This isn't what's happening in this case.

After all, an integer is an integer is an integer, regardless of whether it's in an aspx form or an ascx control.

If I have to do it purely in code, then so be it, it just seems somewhat inelegant when it's handled so seamlessly with the pre-existing tags.

 Thanks anyway.

0
ManchesterCodeMonkey
11/23/2008 8:57:41 PM

ManchesterCodeMonkey:
 I appreciate that, however surely the whole point of the viewstate is to provide a framework that does that for you?

no.   if every page level variable that you used was automatically stuffed into viewstate, then your pages (rendered to the client) would be painfully large.  Also keep in mind that not everything can be put in viewstate unless it is marked as serializable.  Viewstate is something that you need to opt into.  It is not automatic.

ManchesterCodeMonkey:
With a textbox, if I set it's text attribute to 'fred' via code at step 1, at step 3 it is still 'fred'

The textbox retains its Text propertys value due to the forms post data - not from viewstate.  Other properties of that control will persist across postbacks as the control developer placed those values in ViewState explicitly.  i.e   they opted in to viewstate for certain properties.

Your arraylist is a variable that you have created in your class and the framework makes no assumptions about how you intend to handle it.  As a general rule, you do not create control instances and place them in viewstate.  Instead you place information in viewstate that allows you to recreate the dynamic controls on postback.  Remember, any data you place in viewstate is sent to the client browser in a hidden form field.  overusing viewstate can make you page size dramatically large and make you page feel unresponsive.

 


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
11/23/2008 9:10:20 PM
Reply:

Similar Artilces:

Web User Control to Web User Control...
Hi, I have 2 User controls on a page and want Control1 to call a method of Control2. Is this Possible? Example: Con1 = Datalist showing products, each with a Quantity Box and a Button. Con2 = Repeater showing Cart Preview (name, Price) in page.aspx. When I click on the button on the DataList in Con1 it adds the item into the Session based Cart. However it does not update the Cart Preview. I need to call BindPreview() in Con2 in order to update the Cart Preview... Does that make sense? argh! any help much appreciated! PeteWeb Design Nottingham, UK Well I can call BindPreview() from m...

access controls on web user control x from web user control Y
I have 2 web users controls in a page and I would like to get or set the selected values of a few dropdown boxes on web user control X from web user control Y and I also would like to know how to access functions that are on a web user control X from a web user control Y, is this possible? How can I do it? User can access and set the values of the User Control from .aspx page through properties,using javascript and in code-behind of aspx page.The details of it are shown below Using PropertiesIf the Sample.ascx control has two textboxes and submit button.You can access the valu...

How to access individual controls from a form containing the web user control containing those controls
 Below is a block of code in my .aspx form named default.aspx. In this form I load a web user control. I then add it to a place holder control.(Lines 3 and 4 below) So how do I access the individual controls in my web user control? I want to set the properties on those controls, but I am baffled as to how to access the control. For example I have a text label control named "label3". How do I access this control. Because for example, under certain situations I want to hide that control. ( Label3.Visible = false;)  1    if(!Page.IsPostBack) 2&nb...

web controls and web user control
i have a problem in a web form , I have a webform that contains a web user control which in turn contains a html input form ,the web control events don't fire up ,When I click button ,no effect ,I don't know what is the effect of the html form which is in the web user control on the web controls in the web form ?? can any one help me the web control event should be handle in the code behind page, is the event handler for the button you are clicking registered? You can try double clicking the button, should give you the default btn_click event handler in code behind. Also, make ...

Pass data from Web User Control to Web Form
I have a Web Form that contains a Web User Control. The WUC displays dynamic content. I want to change the TITLE property of the Web Form, based on the contents of the WUC. For example, if the WUC displays information about Horses, I want to change the page title to "HORSES" by passing the string to the parent Web Form. I have tried playing with parameters and such, but I can't remember how I did this in the past. PLEASE HELP!~o0 Spin-Monkey Oo~ The best way to do this is by creating a public property on your web user control and accessing that from your web form. Check ...

Problem in accessing web form data in user controls when create user control dynamically
HI. I have a problem using web user control. I designed a user control named NewsForm. This user control contains some web form elements like <asp:textbox>. When I add it in an .ASPX page, all things may be true. I can know which user filles in textbox (for example and other controls) <%@ Register TagPrefix="uc1" TagName="NewsForm" Src="NewsForm.ascx" %> and <UC1:NewsForm id="newsForm" runat="server"></UC1:NewsForm> But when i create it in code behined dynamically, however user control has web form controls but their value are blank for example //aspx co...

Web user control inside update panel replace with another web user control
 Hi there. I have a page with a menu. an and then the content. My thing is. That i have the update panel, and inside that i have a regual panel in which i add the Web User Controls i need. Which all works fine. My problem is. That i i have a submit funcion on almoast all the Web User controls. What i would like is that i inside that update panel, can dispose the original Web user Control and then add a response Web User Control. In normal language. Is there a way that i can load one web user control into antoher and then disposose the original? Thanks in advance hello. well, what ...

UpdatePanel within a web user control resets data of controls outside the user control
Hello, I have a usercontrol on my page which displays a running marquee text. It makes use of an UpdatePanel (within the user control) to refresh the marquee text (within the updatepanel) at periodic intervals. For this I added a timer control and its tick event as an async postback trigger for the UpdatePanel. I have a lot of textboxes and dropdown list boxes (all with runat=server) on the page outside the above user control. These are also contained in different UpdatePanels. Problem is, when the user control does a postback to refresh the marquee text, it causes some of...

Web Form and Web User Control
Hello, I have a Web User Control (ascx) that includes a button. This button has an onclick event method. This Web User control is included into a Web Form. (thru LoadControl). However, when I click on the button, the event method is not executed. What should I include in order it works fine? Thanks in advance. GAA. Using Loadcontrol is using dynamic controls and when using dynamic controls you must recreate the same dynamic controls ono postback to econstruct the page control tree. It is best if you do this during the Page PreInit event. How complex are your controls ...

Single page with multiple user web controls VS Multiple page with specific user web controls
I have a question regarding single page with multiple user web controls vs multiple page with specific user web controls   Option 1: I am of the opinion to have multiple pages with specific user web controls and use an object to store all the information as the user navigates through the application. And finally at the end, read this object and save all the information to the backend database.   Option 2: My respected team member suggests that we have only one page, with all the specific user web controls and not use an object, instead show/hide the user web controls based ...

change layout of web controls in web user control
Hi I have create a user control with 3 asp:textbox in it. I would like to reuse the same 3 textboxes in 2 seperate web pages. In one case I want them to appear in  a row (as search parameters) and in the other I want them to appear in a column(to add a new object)..  Can I do change layouts using CSS or something? Hi,    Here is a solution to your question for your reference. Create a web user control as the following <%@ Control Language="C#" AutoEventWireup="true" CodeFile="DynamicalUserControl.ascx.cs" Inherits="DynamicalUserControl" %><asp:Panel ID="...

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

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

Web resources about - Persisting data in a web user control, which contains a list of other web user controls. - asp.net.web-forms

Pacers' Game 7 Victory Provides Brief Relief from Persisting Chemistry Issues
INDIANAPOLIS—They churned through an awkward blend of emotions Saturday: anxiety and desperation, bravado laced with uncertainty, and a final ...

"There is no human circumstance more tragic than the persisting existence of a harmful condition for ...
"There is no human circumstance more tragic than the persisting existence of a harmful condition for which a remedy is readily available" by ...

Crude Trades Near 5 1/2-Year Low as Supply Glut Seen Persisting
New York Times Crude Trades Near 5 1/2-Year Low as Supply Glut Seen Persisting Bloomberg Benchmark U.S. oil held losses after sliding below ...

With economic problems at home persisting, just what is it that a Democrat is ...
ABC News With economic problems at home persisting, just what is it that a Democrat is ... Chicago Tribune WASHINGTON (AP) — Five months before ...

Uranium Contamination Persisting At Old Processing Sites Despite Remediation
Uranium groundwater contamination at old uranium-ore processing sites is persisting despite remediation of contaminated surface materials two ...

Amid persisting economic duress, worries rise about suicides
High-profile deaths – the latest being the mayor of Springfield, Ill., and the Florida school board shooter – have common backdrops of economic ...

Persisting Data on Android Using SQLite
With a little care, SQLite can be used as a data store or full database on Android devices

Hyundai Motor sees currency risks persisting in Russia, emerging markets
The automaker saw net profit drop 19% last quarter.

Girls' YouTube Rant Highlights Persisting Black/Brown Racism (VIDEO)
There are plenty of disturbing things about anti-African American rant by two teen girls from Gainsville, Florida that went viral on YouTube ...

Why The Shrinking But Persisting Pay Gap Between Men And Women? Pew Research Explains [VIDEO]
Pew Research explains why the hourly pay gap between men and women has narrowed and yet persisted in the last 30 years.

Resources last updated: 11/22/2015 5:05:20 AM