Trying to understand postback with dynamic created controls

Hello,

 I have real difficulty trying to understand how to handle postbacks with controls that are dynamically created. I have a webform in which I create a number of checkboxes dynamically (fillRoles). When I click the save button on my form I execute the btnSave_Click eventhandler that should save my checkbox values into the database. But since the checkboxes are lost at the postback i re-create them, figuring they should regain their state because i create them with the same ID. I guess I've made some amateur designer booboos here. Could somebody please assist? Here is my code:

  

1    using System;
2    using System.Data;
3    using System.Configuration;
4    using System.Collections;
5    using System.Web;
6    using System.Web.Security;
7    using System.Web.UI;
8    using System.Web.UI.WebControls;
9    using System.Web.UI.WebControls.WebParts;
10   using System.Web.UI.HtmlControls;
11   using BusinessLogic;
12   using Telerik.WebControls;
13   
14   public partial class modules_modules_frontend : MyModule
15   {
16       Global global = new Global();
17       DataTable rs = new DataTable();
18   
19       string strRoles = "";
20   
21       void Page_Load(object sender, EventArgs e)
22       {
23           this.EnableViewState = true;
24           if (!IsPostBack)
25           {
26               gridExistingModulesBind();
27               fillRoles();
28               enableRoles();
29               checkRoles();
30           }
31       }
32   
33       protected void fillRoles() /* build roles checkboxes and fill strRoles through DB */
34       {
35           string mod_website_id = "0";
36           if (gridExistingModules.SelectedRow != null)
37           {
38               mod_website_id = gridExistingModules.SelectedRow.Cells[1].Text;
39           }
40           rs = global._dbconnection.GetDataTable("spModModulesFrontendRolesModWebsiteId '" + Session.Contents["website_id"].ToString() + "', '" + mod_website_id + "'");
41           foreach (DataRow row in rs.Rows)
42           {
43               CheckBox cb = new CheckBox();
44               cb.ID = row["role_id"].ToString();
45   
46               if (row["aantal"].ToString() != "0")
47               {
48                   strRoles = strRoles + "[" + row["role_id"].ToString() + "]";
49               }
50   
51               Label lbl = new Label();
52               lbl.Text = row["title"].ToString() + "<BR>";
53   
54               pnlRoles.Controls.Add(cb);
55               pnlRoles.Controls.Add(lbl);
56           }
57       }
58   
59       protected void enableRoles() /* enable or disable roles checkboxes bases on selected value in ddlAccesslevel */
60       {
61           foreach (Control ctl in pnlRoles.Controls)
62           {
63               if (ctl is CheckBox)
64               {
65                   CheckBox cb = (CheckBox)ctl;
66                   if (ddlAccesslevel.SelectedValue.ToString() == "3")
67                   {
68                       cb.Enabled = true;
69                   }
70                   else
71                   {
72                       cb.Enabled = false;
73                       cb.Checked = false;
74                   }
75               }
76           }
77       }
78   
79       protected void checkRoles() /* check or uncheck checkboxes bases on the strRoles string */
80       {
81           foreach (Control ctl in pnlRoles.Controls)
82           {
83               if (ctl is CheckBox)
84               {
85               CheckBox cb = (CheckBox)ctl;
86                   if (strRoles.LastIndexOf("[" + cb.ID + "]") != -1)
87                   {
88                       cb.Checked = true;
89                   }
90                   else
91                   {
92                       cb.Checked = false;
93                   }
94               }
95           }
96       }
97   
98       protected void gridExistingModules_Select(object sender, EventArgs e)
99       {
100          string mod_website_id = gridExistingModules.SelectedRow.Cells[1].Text;
101          rs = global._dbconnection.GetDataTable("spModModulesFrontendGetItem '" + gridExistingModules.SelectedRow.Cells[1].Text + "'");
102  
103          tbDescription.Text = rs.Rows[0]["description"].ToString();
104          tbCssPostFix.Text = rs.Rows[0]["csspostfix"].ToString();
105          tbPosition.Text = rs.Rows[0]["position"].ToString();
106  
107          ListItem li = new ListItem();
108  
109          ddlModules.ClearSelection();
110          li = ddlModules.Items.FindByValue(rs.Rows[0]["mod_id"].ToString());
111          if (li != null) { li.Selected = true; }
112  
113          ddlContainers.ClearSelection();
114          li = ddlContainers.Items.FindByValue(rs.Rows[0]["container_id"].ToString());
115          if (li != null) { li.Selected = true; }
116  
117          ddlAccesslevel.ClearSelection();
118          li = ddlAccesslevel.Items.FindByValue(rs.Rows[0]["accesslevel_id"].ToString());
119          if (li != null) { li.Selected = true; }
120  
121          changeStatus("edit");
122          
123          fillRoles();
124          enableRoles();
125          checkRoles();
126      }
127  
128      protected void changeStatus(string _status)
129      {
130          if(_status == "addnew") {
131              gridExistingModules.SelectedIndex = -1;
132              ddlModules.ClearSelection();
133              ddlContainers.ClearSelection();
134              ddlAccesslevel.ClearSelection();
135              tbDescription.Text = "";
136              tbCssPostFix.Text = "";
137              tbPosition.Text = "";
138              ddlModules.Enabled = true;
139              btnDelete.ImageUrl = "~/admin/images/delete_disabled.png";
140              btnDelete.Enabled = false;
141          }
142          if(_status == "edit") {
143              ddlModules.Enabled = false;
144              btnDelete.ImageUrl = "~/admin/images/delete.png";
145              btnDelete.Enabled = true;
146          }
147      }
148  
149      protected void gridExistingModulesBind()
150      {
151          rs = global._dbconnection.GetDataTable("execute spModModulesFrontendExistingGet '" + Session.Contents["website_id"].ToString() + "'");
152          gridExistingModules.DataSource = rs;
153          gridExistingModules.DataBind();
154      }
155  
156      protected void btnNewModule_Click(object sender, EventArgs e)
157      {
158          changeStatus("addnew");
159          fillRoles();
160          enableRoles();
161      }
162  
163      protected void btnSave_Click(object sender, EventArgs e)
164      {
165          fillRoles();
166          string mod_website_id = "";
167          if (gridExistingModules.SelectedRow != null)
168          {
169              mod_website_id = gridExistingModules.SelectedRow.Cells[1].Text;
170              global._dbconnection.Execute("execute spModModulesFrontendUpdate '" + gridExistingModules.SelectedRow.Cells[1].Text + "', '" + tbDescription.Text + "', '" + tbCssPostFix.Text + "', '" + tbPosition.Text + "', '" + ddlContainers.SelectedValue + "', '" + ddlAccesslevel.SelectedValue + "'");
171              gridExistingModulesBind();
172          }
173          else
174          {
175              rs = global._dbconnection.GetDataTable("execute spModModulesFrontendInsert '" + Session.Contents["website_id"].ToString() + "', '" + ddlModules.SelectedValue + "', '" + tbDescription.Text + "', '" + tbCssPostFix.Text + "', '" + tbPosition.Text + "', '" + ddlContainers.SelectedValue + "', '" + ddlAccesslevel.SelectedValue + "'");
176              mod_website_id = rs.Rows[0]["mod_website_id"].ToString();
177              gridExistingModulesBind();
178          }
179          foreach (Control ctl in pnlRoles.Controls)
180          {
181              if (ctl is CheckBox)
182              {
183                  CheckBox cb = (CheckBox)ctl;
184                  int value = 0;
185                  if (cb.Checked) { value = 1; }
186                  global._dbconnection.Execute("spModModulesFrontendRolesUpdate '" + Session.Contents["website_id"].ToString() + "', '" + mod_website_id + "', '" + cb.ID + "', '" + value + "'");
187              }
188          }
189      }
190  
191      protected void btnDelete_Click(object sender, EventArgs e)
192      {
193          GridViewRow row = gridExistingModules.SelectedRow;
194          global._dbconnection.Execute("spCoreDeleteModWebsiteId '" + row.Cells[1].Text + "'");
195          gridExistingModulesBind();
196          changeStatus("addnew");
197          fillRoles();
198          enableRoles();
199      }
200  
201      protected void btnCancel_Click(object sender, ImageClickEventArgs e)
202      {
203          changeStatus("addnew");
204          fillRoles();
205          enableRoles();
206      }
207  
208      protected void ddlAccesslevel_SelectedIndexChanged(object sender, EventArgs e)
209      {
210          fillRoles();
211          enableRoles();
212      }
213  }
214  
Kind regards,
 Glen

0
siro
4/13/2007 1:19:11 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

5 Replies
543 Views

Similar Articles

[PageSpeed] 26

I think the problem is in where you are re-creating the checkboxes.  They have to be created by a certain point in the page-lifecycle for their values to be saved.  The button's event handlers executed too late.  All values are restored by that point.  If you create the checkboxes each time the page loads in the Page_OnLoad event, that should do the trick.  Something like this:

 
21       void Page_Load(object sender, EventArgs e)
22       {
23           this.EnableViewState = true;
24           fillRoles();
25           if (!IsPostBack)
26           {
27               gridExistingModulesBind();
28               enableRoles();
29               checkRoles();
30           }
31       }
 
 I"m not sure if you will have to change anything in the fillRoles() method for this approach to work.
0
Benners_J
4/13/2007 3:00:48 PM

 

Just a note...

Page_Load is too late in the lifecycle...the controls need to be recreated in Page_Init, so that they are there ready for when asp.net processes the request.form object / viewstate.


Please remember...if the answer provided helped to solve the problem, mark it as 'answer' !
0
roy_huntley
4/13/2007 4:04:11 PM
roy_huntley:

 

Just a note...

Page_Load is too late in the lifecycle...the controls need to be recreated in Page_Init, so that they are there ready for when asp.net processes the request.form object / viewstate.

Thank you for the clarification.  If the control is created in the Page_OnLoad, any values posted through the form will be saved (such as a textbox's text, or a checkboxes checked state), but the ViewState won't be saved.  For example, if you change the text color, or hide the control, that won't be saved.

It is probably better to always use the Page_Init event so you don't run into problems where it seems like only half of the control is working.  Those can be some of the most frustrating to figure out Big Smile

0
Benners_J
4/13/2007 4:47:56 PM

This is incorrect.

Benners_J:
roy_huntley:

Just a note...

Page_Load is too late in the lifecycle...the controls need to be recreated in Page_Init, so that they are there ready for when asp.net processes the request.form object / viewstate.

Thank you for the clarification.  If the control is created in the Page_OnLoad, any values posted through the form will be saved (such as a textbox's text, or a checkboxes checked state), but the ViewState won't be saved.  For example, if you change the text color, or hide the control, that won't be saved.

It is probably better to always use the Page_Init event so you don't run into problems where it seems like only half of the control is working.  Those can be some of the most frustrating to figure out Big Smile

You can recreate your controls in Page Load. The real issues with doing so are more related to the control tree and how it is built, or has been modified, and what INamingContainer your dynamic controls are children of. Ecetera at the end might mean little, but there are some issues.

Certainly it is too late to re-create the controls during the Control Events stage and the best time to ReCreate dynamic controls is on PreInit, but this requires control or record count persistence to a hidden field (ViewState is not yet available in PreInit).

It is best not to hit the DB to recreate your controls, it is best to simply recreate the control tree based on the number of controls for a known number of records. Then to allow viewstate to restore the controls state information - actually let the control restore it from viewstate.

I have not yet reviewed your code fully.


Rgds,
Martin.

For the benefit of all users please mark any post answers as appropriate.
0
mokeefe
4/14/2007 3:29:24 PM

On review your additonal problem is in the merging of the control creation with the control binding / setting of values. What you need is a method that creates the controls and provides you with a reference that enables you to set the control values afterwards. - in your case the equivalent to databinding is when you are orignally creating the controls not re-creating for value persistence from ViewState.

As you are setting Checkbox ID's explicitly, not my preferred but used in my example below, you should not have a problem with other dynamic controls on the page or control re-creation.

This - 

foreach (DataRow row in rs.Rows)
           {
               CheckBox cb = new CheckBox();
               cb.ID = row["role_id"].ToString();
   
               if (row["aantal"].ToString() != "0")
               {
                   strRoles = strRoles + "[" + row["role_id"].ToString() + "]";
               }
   
               Label lbl = new Label();
               lbl.Text = row["title"].ToString() + "<BR>";
   
               pnlRoles.Controls.Add(cb);
               pnlRoles.Controls.Add(lbl);
           }
 

Review this example where I am using a boolean parameter to determine if I should be incrementing my control counter. This enables me to use the same method to re-create the controls on postback without hitting the datasource.

I can't find a better one in C#, I do have them out there but where? If the point is not really clear enough here in VB.Net I can provide a better C# example with sample Data Access etc. Particularly as the data access implications (improvements) may not actually be very clear in this example.

http://forums.asp.net/thread/1623106.aspx

Please advise.

 


Rgds,
Martin.

For the benefit of all users please mark any post answers as appropriate.
0
mokeefe
4/14/2007 4:02:49 PM
Reply:

Similar Artilces:

postback from dynamic controls to create more dynamic controls
Hi, Could any one help me?  I have a masterpage with dynamically created list boxes.  When the user selects an item from the listbox the selected value will be used to dynamically create a set of controls in the contentplaceholder.  The problem i have is that the item selected from the list box is posted back and i do not know what the selected item is until the life cycle is complete.  During the post back is there a way to findout which listbox control performed a post back and its value before i get to the init part of the content page where i woul...

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

Dynamically creating controls in Web forms
I am able to create a web control programmatically and display on the form. In the click event of the button then I am trying to capture the value entered in the above created textbox in another click of button but I am unable to obtain the reference of the control that has been created dynamically. Can anyone help me please? protected System.Web.UI.WebControls.Panel myPanel; private void btnMake_Click(object sender, System.EventArgs e) { TextBox txtBox = new TextBox(); myPanel.Controls.Add(txtBox); } private void btnGotValues_Click(object sender, System...

Dynamically created controls in web form
Hi there. This is bit of an open ASP.Net (C#) question with regards to dynamically created controls and in particular tabular or panel controls. What I currently have is a web page that creates between 1 and 6  tables, each of which holds specific data about a set of products, each table (or panel, if you want) has a couple of multi-line TextBoxes and a few other controls, all lined up in a set format. The number is determined by the data records returned from a database table. My question is what is a best way to create these tables of data at run time?  Has anybody else had e...

dynamically creating html controls on web form
hello all, I'm creating html <input type="file" name="test" id="test" runat="server"> dynamically using Javascript on a .aspx page. when i submit the form i get Javascript "Access is denied" error. if i take out name attribute from input tag in javascript -  it is not throwing any javascript error but the file is not being uploaded to the server. Can anyone point me in the right direction? Thanx in advance     Maybe this is a security restriction imposed by the browser? I know there are several constrain...

Dynamic web forms
  I am asking a question on my web form. Based on the answer I want to display additional text boxes for the users to fill out. visible false, then visible true on postback. The problem is that the validation controls are seen on postback.  I can image why this happens.   How do I work around this issue, so that when the additional textboxes are posted back, the validation controls are not seen, until  or when the user has inputed invalid data into the textbox?    Thanks    otai Have you set the textboxes Visible parameter to false and ...

Vb.net win forms- dynamically created controls
i'm having this issue with setting events on dynamically created controls in vb.net windows forms. i would really appreciate if some of you could stop by and check this out for me. if you have any comments please feel free to post them here. http://www.webwizguide.info/wwf_forum/forum_posts.asp?TID=10590 thanks in advance Paul A Morgan Webmaster: http://www.illgetit.info/ no. lame. re-state this question dumbass.Kay LeeMySpace.com - http://www.myspace.com/kragieInfrastructure GroupMySpace.com- Code to live, but Live to code....

How to generate dynamically Web Form Controls without doing Postbacks?
I need some experienced advice for this subject. I want to generate dynamically web form controls from my aspx VB.NET page without doing Postbacks. Which is the best way of doing this? Because if I generate the form controls from a JavaScript function these form controls are Html form controls, so it doesn’ t have the same functionality and advantages than ASP.NET form controls have. For instance I can’t do server validations, the state of the entered form data doesn’ t persist after Postbacks, I can’t reference them from an ASP.NET subroutines and do operations with them, etc… Now...

dynamically created control not being created on postback
I am trying to create some dynamic controls and get the values on postback for some reason I cant get a control to create on postback  - -- simplified the code only to create a label control on postback.  works fine firsttime through but not on postback. any ideas what would stop a label control from being dynamically created on postback and added to a place holder?       Hi, can you provide the relevant parts of your code or a specially crafted test page that has the problem? That helps us, members on these forums, to more quickly find out what'...

error trying to create web form from visual studio.net
I get the following message when I try to create a web form from visual studio. Visual Studio.NET has detected that the specified web server is not running ASP.NET version 1.1. You will be unable to run ASP.NET web applications or services. I downloaded and installed ASP.NET version 1.1. Why am I getting this message? Thanks, Keith Stallings Try running aspnet_regiis -i from the .Net Framework's bin directory to see if it corrects the problem....

Create Dynamic Dropdownlist Controls / How to Create Dynamic Dropdownlist Controls
Hi,    This might be useful for someone who strucks with create dynamic dropdownlist/ controls. In ASP.Net is page is stateless. when you are creating the dynamic dropdownlist control following issues you might be facing, 1. After loaded the control, on selected index changed event the control will be disappear. 2. The selectedIndexChanged raised event might not be fired when selection of Dropdownlist. 3. Locate the exact dropdownlist which you created dynamically. 4.Placing this dynamic controls in exact location in the page. Solution: You have to re-create the con...

create and add controls dynamically to dynamically created Table Control
How can i create web server Table control dynamically with vary number of  rows and columns, and  then adding  further  other controls(like  dropdown, Text box etc.)  randomly to the specific created Table Cells. First of all you should use PlaceHolder control to add Table control to it:<asp:PlaceHolder id="PH" runat="server"></asp:PlaceHolder>Code Behinde:Table t = new Table();TableRow tr = new TableRow();TableCell td = new TableCell();//td.Text = "Hello, I am a TD";// Here well create TextBox and add it to TDTextBox txt = new TextBox();tx...

Postback and dynamically created controls (it's not the "control no longer exists after postback" problem)
Hello, I'm working on a simple application, there is a TreeView, each node of the tree have differents properties so it is displayed differently. I decided to use Web User Controls (.ascx) to display the differents types of nodes. When I click a node, the corresponding ascx is loaded. Since the ascx need postback I use the ViewState to store the name of the current ascx, in the OnLoad method I load it again so the callback works. Problems appeared when I wanted to add a Datagrid (with a "Delete" button on each row) in one ascx. I have a Web User Control (Users/View.as...

form action when dynamically create form control
Hi, When I use <asp:literal> in my form and render it as a iframe during runtime,everything is fine except it always automatically add action attribute to the form and set the attribute's value to the iframe src attribute.How can I remove(avoid) this action attribute being generate because it causes some weird problem.Thanks Hi there, Can you post a code sample of what's going on? I'm not following where the action attribute comes into play here. Thanks.--Brian DesmondWindows Server MVP - Directory Serviceshttp://www.briandesmond.com In the pageload,I have the following code:...

Web resources about - Trying to understand postback with dynamic created controls - asp.net.web-forms

Resonate Social For Facebook Helps Advertisers Understand Users’ Motivations
Why do Facebook users make the decisions they make? Resonate wants to help advertisers find out, so the digital marketing outfit launched Resonate ...

Facebook PMD Gigya releases Consumer Insights to better understand user identities
... allows marketers to easily query Gigya’s Identity Storage database and tie identity information with key performance indicators to understand ...

Genius by Rap Genius — Search and understand the meaning of song lyrics, poetry, literature, and news ...
Get Genius by Rap Genius — Search and understand the meaning of song lyrics, poetry, literature, and news on the App Store. See screenshots and ...

All sizes - Understand Abundance & Breath - Flickr - Photo Sharing!
Flickr is almost certainly the best online photo management and sharing application in the world. Show off your favorite photos and videos to ...

Kate Micucci & Tony Thaxton - "Puppets Understand" - YouTube
Subscribe for more Nerdist Presents: http://nerdi.st/subscribe Written and Performed by KATE MICUCCI & TONY THAXTON Watch Duo: http://youtu.be/Tj5RLliHNMQ ...

Scientists continue search to understand Mers
The Mers coronavirus continues to confound scientists. To better understand the disease and determine where it comes from, a new project set ...

Explainer Video of the Day: Author John Green Helps You Understand Boko Haram
... in the news, but the situation in Nigeria with the Islamist terrorist group Boko Haram often gets overlooked and can be difficult to understand. ...

The Aussie rules love affair and one who can't understand it
Football (the AFL variety) and I have always had a tumultuous relationship. I've never really understood its allure, but it's always been there, ...

14 Accounting Terms Everyone In Small Business Needs To Understand
Like any profession, accounting has what seems to be impenetrable jargon to outsiders. But, also like most professions, the jargon is just shorthand ...

Tony Abbott doesn't understand the China challenge
The Australian government's new attitude towards China's foreign policy underestimates that country's determination to change the geopolitical ...

Resources last updated: 12/24/2015 12:01:14 AM