Dynamically Loading User Control and Maintaining its viewstate. And Getting Values from the control.

 I have a drop down which is populated on the page looad.  When i select an item from drop downlist i get to see two listboxes with add/removing the objects from one left to right listbox and below that i have a user control which should be populated dynamically based on the selectedvalue from drop down list.  So there are three sections that are seen once a selected value is consiedered from drop down list.  Now I am getting the user control using the below code given

case "42": viewRequired = "vw_AncCostSavingsByCarrier_adhoc";
                Control CostSavingReportUserControl = (User_Controls_CostSavingReport)LoadControl("~/User Controls/CostSavingReport.ascx");
                PanelUserControl.Controls.Add(CostSavingReportUserControl);
                ViewState["ReportTitle"] = "Non Pharmacy Cost Savings Report";

 Which is a switch case as i have n number of user controls.  But i am unable to get the values the user entered into that control on the button click event down that user control. And when user clicks and Add/Remove button to add/remove items from one to another this controls is going visible, So i have reloaded that user control once again.  But the questions is ia m unable to get the values entered into the user control.  What could be the best way in getting the values from the user control which is added dynamically.

What i want is getting the value from user control.  Secondly i dont want to register any user control in the aspx(if possible).  Above  code (User_Controls_CostSavingReport) is the user control i casted to which is not needed as control only needs the virtual path.  So i am able to load user control, and reloading if add/remove the buttons for selecting/removing items from listbox.  And finally user enters values which i need to get.  I want the values to remain in the user control even after the button click is done which actually needs these values from user control and generate a report in a new page.

 Any Kind of help would be greatly appreciated. 

Thanks,

Suman

0
rayabharapusuman
9/22/2008 1:44:56 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

6 Replies
1196 Views

Similar Articles

[PageSpeed] 49

which event r you using ? some time you get value in page_prerender event. and It can be solved by adding custom event/delegate to user control. well can you post ur aspx.cs code?

Anuj Patel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If this post answers your question please mark it as Answered.
0
AjPtl
9/22/2008 2:57:36 PM

Asp.Net does not maintain the control tree, if you have programmatically added controls then you have to maintain them yourself. This means you have to add them to the control tree on every round trip.
All ViewState does is keep properties of your controls and reaplly them during round trips and this is based on control ID so be carefull to give the controls the same ID's.
Please create a simple example where you have a button that creates a textbox and in the click event after creating the textbox say something like: ViewState[<key>]=<value>; then in the page load event test if that key value pair exists and if the value is what it should be and recreate the textbox. Also add another button to test the value in that textbox, you'll see this solves the problem and the value is correctly displayed.

button1_Click(...)
{
  TextBox txt=new TextBox();
  txt.ID="txt";
  Page.Controls.Add(txt);
  ViewState["txtadded"]=true;
}

Page_Load(...)
{
  if(ViewState["txtadded"]!=null)
  {
    if((bool)ViewState["txtadded"] { button1_Click(button1, EventArgs.Empty); }
  }
}

Let me know if this helps, if you have any trouble I can send you an working example to see what I'm talking about.

Regards

0
Doly
9/22/2008 3:02:45 PM

 can you please send me some working samples.  It could be of great help for me. 

situation is i have a user control for every report which should be loaded each time that report link is selected on the same page.  How i achieved this task is by hiding all the user controls in the design and setting the visibility to false.  And used delegates and event handlers to make the button click event of that user control and also the parametres to pass to aspx from that user control.  So i think my page size is going to increase if i go on and on.  So i just want to get rid of this situation.

 

Please send me if you have any samples.

Thanks.

 

0
rayabharapusuman
10/1/2008 2:45:35 PM

 

1    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
2    
3    <%@ Register Src="HeaderMenu.ascx" TagName="HeaderMenu" TagPrefix="uc1" %>
4    
5    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6    
7    <html xmlns="http://www.w3.org/1999/xhtml" >
8    <head runat="server">
9        <title>Untitled Page</title>
10   </head>
11   <body>
12       <form id="form1" runat="server">
13       <div>
14           <div id="div_Content" runat="server"></div>
15           <asp:Button ID="Button_Insert" runat="server" Text="Insert" OnClick="Button_Insert_Click" />
16           <asp:Button ID="Button_Read" runat="server" Text="Read Value" OnClick="Button_Read_Click" /><br />
17           <asp:Label ID="Label_Value" runat="server"></asp:Label>
18        </div>
19       </form>
20   </body>
21   </html>
 
1    using System;
2    using System.Data;
3    using System.Configuration;
4    using System.Web;
5    using System.Web.Security;
6    using System.Web.UI;
7    using System.Web.UI.WebControls;
8    using System.Web.UI.WebControls.WebParts;
9    using System.Web.UI.HtmlControls;
10   
11   public partial class _Default : System.Web.UI.Page 
12   {
13       protected void Page_Load(object sender, EventArgs e)
14       {
22           if (ViewState["_txt"] != null)
23           {
24               if ((bool)ViewState["_txt"]) { Button_Insert_Click(Button_Insert, EventArgs.Empty); }
25           }
26       }
27       protected void Button_Insert_Click(object sender, EventArgs e)
28       {
29           div_Content.Controls.Add(new TextBox());
30           ViewState["_txt"] = true;
31       }
32       protected void Button_Read_Click(object sender, EventArgs e)
33       {
34           Label_Value.Text = ((TextBox)div_Content.Controls[0]).Text;
35       }
36   }
 
0
Doly
10/2/2008 6:54:15 AM

 Thank You doly for the information given.  Every user control has its own button in it.  So i load that user control in a drop downlist selected index changed event. (I show two list boxes with ability to transfer data from one listbox to other like add/remove buttons between those two listboxes and also under neath that i get the user control loaded.)  Now when the user hits on add or remove buttons he should be able to see the same user control and should not loose any data if he has entered into it.

 Now i want to raise the button click event for that user control (each user control has its own submit button.) and get its values in that click event.  Suggest me if i can use a common button for all the reports or keep that in the user control.  And how can i get the values in that user control.

Generally for single user control i can use the delegates and eventargs to pass the values of that user control.

 In the code sent by you you Viewstate for _txt is always null as it is in pageload event and it means that it will always be null.

Secondly i did not understand why you are using two buttons..hope you got my situation. Please let me know if you need anything from me..I am in real hard situation to do this.

 Any help would be greatly appreciated.

 Thanks,

Suman

0
rayabharapusuman
10/2/2008 10:17:16 PM

Hy,
This is just a simple example of how I handle programmatically created controls, this makes theese controls behave just like declarative ones.
Please insert break points in that Page_Load event and you'll see that ViewState["_txt"] is not allways null. Basically what I'm doing there is checking to see if the control has been created and if it has been created then recreate it on every roundtrip.


I will try to create an example of what you are trying to do: a DropDownList that on SelectedIndexChanged event loads a user control that contains 2 ListBoxes and 2 buttons that can move Items from one to the other and a third submit button.
I will get back to you once I'm finished with this example.

 Regards

0
Doly
10/3/2008 7:03:22 AM
Reply:

Similar Artilces:

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

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

How get value from a dynamically created control in a user control
HI, I am working with a version of IBuySpy. On one page is a form that contains a user control that lists the items the user purchased, the subtotal, shipping, etc. I wanted to add a DropDownList from which the user could select the shipper. The dropdown list works fine as long as it has .AutoPostBack = false. However, I cannot figure out how to get the value that the user selected when they finally press the submit button on the form. All attempts to locate the control and it's value have failed. I tried drillingdown from the form to the child controls, and sub child controls. N...

How to maintain form controls value after user control post back?
 hello experts, I have created filter grid in asp.net & C#.My form design has contains 3 dropdown controls and Filter grid(User control).Its working fine(filter), but one problem arise.the form controls are clear when i filter a grid(post back).I tried to reterive values using view state, hidden controls, i got only null values.Anyone please help, its urgent to me. Its my user control code.FilterGrid.aspx<%@ Control Language="C#" AutoEventWireup="true" CodeFile="FilterGrid.ascx.cs" Inherits="FilterGrid" %><style type = "text/css&...

complicated dynamic controls problem and viewstate in web user control
I am creating a web user control. This web user control essentially functions as the checkboxlist control does, but is an extension. I am creating functions that let you get the number of boxes checked, add checkboxes dynamically, remove then dynamically, etc. So, I have the parent page do something like the following to add a checkbox: Dim myCheckBox as new Checkbox ''''set the checkbox properties ''''add it to my web user control JCheckBoxList.addCheckBox(myCheckBox) OK, my problem is that, if I create the checkboxes in this way, then they will have no viewstate. This m...

when loading a previously created record on to form, some controls are missing values(controls are depended on values selected in other controls)
Hello - I have created a page for Editing records.  this page will open up a chosen record and allow user to edit the data.On the form, I have 3 drop down lists.   The second dropdown list should fill values depending on value chosen in first dropdown list.  The third dropdown list should show/fill values depending on value chosen in second dropdown list.So taking this into count, i have several records with various data.  When I open-up/load a record in Edit form, only the first dropdown list has a value selected that was the pre-existing va...

Getting values from dynamically loaded User Control
I have a user control (orderRow.ascx) that contains 2 dropdownlists and a text box. (ddlProduct, ddlModelNumber, txtQuantity) This is used in an order form, and the control represents each item a user is ordering. I can retreive the values easily enough (orderRow.Quantity) if the control is placed on the form with an ID of orderRow. My question is, If I load the control dynamically, how do I retrieve the values entered in the control for each instance of the control? Do you mean preselect the values?Sarahttp://www.ilovecode.com What I mean is, suppose a user chooses a item fr...

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

Reading form values in dynamically created child controls in a user control
I have a common problem for which I've searched the web for answers for hours to no avail. I have some radiobuttonlists ,dropdownlists,checkboxlists and text controls in a user control. The lists are created statically, however the items in the lists are populated at run time. The lists are displayed in default.aspx (the containing page) and populated on the Page_Load event of the user control .ascx file based on an external data source containing arrays of data. I want to be able to read the values selected by the user from deafult.aspx, the parent page. details: The .ascx...

dynamically load user control from another user control
Is it possible to dynamically load a user control from another user control?  I have an aspx page where I have declaratively included a user control.  Now, within that user control I want to dynamically load another usercontrol onto the page based on some business logic.  Does this even make sense? So, here's the scenario:aspx page:<%@ Register TagPrefix="header" TagName="links" Src="~/usercontrols/toplink.ascx" %><asp:Content ID="ContentBody" ContentPlaceHolderID="cphBody" runat="Server">  ...

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

Web page .aspx is slow when loading. Pages have web user controls on them that are loaded dynamically
I have written a web application using VS 2003. Several of my forms have web user controls on them. The controls are loaded dynamically at runtime. The problem is that the web pages are very slow to load. Does anyone know if there is a way to speed up the pages being loaded into the browser? Here is an example of some code I use to dynamically load the controls:  private void Page_Load(object sender, System.EventArgs e)  {   // Put user code to initialize the page here   // Put user code to initialize the page here    Co...

dynamically load user controls within a user control problem
I am dynamically loading a set of user controls from within a user control (static user control). I add my user controls, at runtime, to the controls collection of a Panel control that is on my static user control. I reload my dynamic user controls each time my static user control runs its Page_Load event. Everything works fine, but my dynamic user control button events do not fire. Any help appreciated.   Regards, Paul. Hi,  how and where do you add the event handler to your user control button? I have a page (aspx) that has a user control (static) on it...

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 resources about - Dynamically Loading User Control and Maintaining its viewstate. And Getting Values from the control. - asp.net.web-forms

Placebase team at Apple file “Schematic Maps” patent dynamically detailing important data
In a report from Computerworld way back in 2009, we learned that Apple had quietly acquired Maps API company Placebase. Then, founder of Placebase ...

Apple's Lightning port dynamically assigns pins to allow for reversible use
... a closer look at how Apple's new Lightning connector works, and has come to the conclusion that the 8 pins on each side of the plug are dynamically ...

In a dynamically typed language, is it a bad idea to return different data types?
In some cases, returning different types from a single function works.

Urlbox Launches Screenshots-as-a-Service Platform to Dynamically Update Galleries
... changes. Launched yesterday, Urlbox allows anyone with a gallery displaying website screenshots to automate the process and keep them dynamically ...

Everything.me launcher dynamically adapts to what you’re doing right now
... phone according to what you’re doing. Perform a search for ‘football’ and your background will change to the NFL logo. A launcher that dynamically ...


A YouTube Experiment Resizes the Player Dynamically
There's a new YouTube experiment that changes the video player's size, depending on the browser window's size. When resizing Chrome's window, ...

Apple Granted “Dynamically Changing Cursor for User Interface” Patent, Originally Filed in 2003
... a utility patent that covers the use of the mouse cursor that changes according to the context of the task it is engaged in. Called a “Dynamically ...

Atmel's FPSLIC II Dynamically Reconfigurable SoC Supports "Silicon-Sharing" For Peripherals & Interfaces ...
Silicon-Sharing Fits 200K Gate Design into 40K Gate FPSLIC II's, Cuts Power Drain by 97%

Everything.me Launcher Wants to Dynamically Change Phones Based on Location, Interests, and Mental State ...
What if your phone’s launcher dynamically changed based upon interests, your location, or topics you had in mind at a specific moment? A new ...

Resources last updated: 12/17/2015 6:46:32 PM