.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

state for programmatically generated controls

Posted By:      Posted Date: April 14, 2011    Points: 0   Category :ASP.Net

I've got a web page that includes a user control.  The page represent an order and the user control represents the line items.  Since the number of line items can be modified, the user control is programmatically creating an HtmlTable for formating and some associated WebControls for each line.  To add a line, I add an empty HtmlRow and the corresponding WebControls to the table.  The question is how do I manage state for these programmatically created controls and how can I query their values on post back?

The EnableViewState property is set for all WebControls, but how to find these controls on post back? Is it valid to cache a pointer to a TextBox in session state when creating a page (i.e. will the pointer be valid on post back)? Do I have to save the values of all of the controls into session state?

I've tried using FindControl() using both the ID's I gave and the ones that show up in the page source, but both return null.

View Complete Post

More Related Resource Links

How to programmatically add controls to Windows forms at run time by using Visual C#

Create a Windows Forms Application
Start Visual Studio .NET or Visual Studio 2005 or a later version, and create a new Visual C# Windows Application project named WinControls. Form1 is added to the project by default.
Double-click Form1 to create and view the Form1_Load event procedure.
Add private instance variables to the Form1 class to work with common Windows controls. The Form1 class starts as follows:

Adding client event handlers to an ASP.NET controls programmatically



I want to add client event handlers to ASP.NET controls (For example: GridView/Button ) programmatically to ASP.NET.

I am aware of "onclick" event handler, so my code would be

GridView1.Attributes.Add("onclick", "JSGridViewFunction()");

Button1.Attributes.Add("onclick", "JSButtonFunction()");

I want to know what are all the event handlers that are available for (or that can be added to)  ASP.NET controls.

For example, I want to add "onsort" event handler to ASP.NET GridView control.

But the following code fails

GridView1.Attributes.Add("onsort", "JSGridViewFunction()");

Please help.


Generated controls - skipping focus event - C# + JS


Ok, here is my senario.

A random (6-15) amount of textboxes are generated. Each textbox represents only one character. From those textboxes, three of them (at a random position) are enabled and the rest disabled.


When I put a character in any enabled textbox, it must put the focus on the next enabled textbox.


Textbox IDs go from 'char0' to 'char15' OR 'char0' to 'char12' OR ...

All the textboxes are generated so I can't set up specific focus events for each textbox because the designated control is unknown at design time.

Here is my attempt:


<script type="text/javascript">
    function abc(nextfocus)


for (int i = 0; i < focusableControls.Length-1; i++)
focusableControls[i].ClientSideEvents.KeyDown = "abc(" + focusableControls[i + 1].ID + ")";


focusableControls is an array with all the textboxes in that can get focus. It is also in the right order.

Things I want to find out:

How will I send the textbox out of focus

Programmatically Generated Reports (RDLC) ASP.NET C#

Good Day,   I been looking for a day now and I couldn't find a good source of information. I have a one of a kind report wherein the RDLC file including all controls are programmatically generated (system generated)  by one of my asp.net page. All fields and its values to be displayed on the RDLC file are coming a stored procedure. On my stored procedure I'm using a temp table for example #MyTable and its columns can adjust programmatically/automatically base on date range. BTW I'm using C# code to generate the RDLC file and preview it on the report viewer of a page. Sample: Date Range: 01/01/2008  to 12/31/2009  My temp table may look like below AssetCode, Description, Class,  Jan2008, Feb2008, Mar2008 --> until column reach Dec2009 AAAA00001, AAAAAAA,FF, 0.00, 0.00,1,00.00 --> some month#### column may not or may contain value base on my formula. AAAA00002, BBBBBBB,FF, 0.00, 1.00,1,00.00 --> some month#### column may not or may contain value base on my formula. AAAA00003, CCCCCCC,CE, 1.00, 1.00,1,00.00 --> some month#### column may not or may contain value base on my formula. I have no problem in retrieving all data on SQL Server using temp table and showing it on a system generated rdlc file even if I'm using

VS2008 and C#: How to create PictureBox controls programmatically in a FlowLayoutPanel ?

I am trying to create multiple PictureBox controls in a FlowLayoutPanel programmatically. The number of the PictureBox controls is dynamic depending on the target image folder. My current approach results a compilation error:             // (Works !)             pictureBox1 = new System.Windows.Forms.PictureBox();             pictureBox1.Width = 150;             pictureBox1.Height = 150;             flowLayoutPanel.Controls.Add(pictureBox1);             string sFileFullName = "Resources\\file1.bmp";             pictureBox1.Image = Image.FromFile(@sFileFullName);             // (Error !)             string pbName = "pictureBox";             for (int i = 0; i < 100; i++)             {             

Maintain Controls State on Master Page.

I have Web Application which uses the Logged In User (Authenticated User) to query his Profile Data from Adabas/Unix using OLEDB. The application provides the user with about 21 different pages (Basic Info, Employment Info, Education, Dependants, Financial Info ...). The web application has a master page, and each profile data page is based on a User Control loaded in the Child ASPX Page. Since we are migrating our legacy applications from Adabas/Unix to SAP, the development Team has prepared web services to query for the same Profile Data from SAP using Web Services. Now, we have to modify the web application to consume the web services instead of using OLEDB to query Adabas. Since we are in the testing phase, and we have only very limited data in SAP, I have to provide temporary control to allow test query the Staff Profile for a Specified User (instead of the Authenticated User) and to select the Source: 1. SAP, or 2. Adabas.   So I am thinking to add the following "Control Section" in the Master Page:<div runat="server" id="divSAPTest" class="SAPTest"> <span>Test SAP Web Services. Enter Staff ID: </span> <asp:TextBox ID="txtSAPStaffID" runat="server" Width="60px"></asp:TextBox> <span>From: </span> <asp:DropDo

Cannot retrieve values of dynamically generated controls

Hi All, I am creating a user control which contains checkboxes and labels that needs to be created on fly. The dynamic generation of these controls depend on the values retreived from a SPlist. I have several panels that display items queried from the list on the basis of a selection criteria. On a button click event I need to capture all the selected values from the controls that were generated dynamically.  When I traverse each dynamic control that I added to the panel, I dont see their values. I tried using recursive retrieval of the control from the page as well but it just behaves crazy, it treats a radio button as a checkbox and returns a value that I am not looking for. I am not using the the page_load() or any other event, I use the button handler on my custom method. I was thinking for ViewState, ControlsState or SessionState. I assume ViewState may not work on this as the dynamically generated controls need to be in the page_load event. Please guide as this getting way more complicated than what I had ever thought of it to be.

Programmatically generated AsyncFileUpload does not fire UploadedComplete event


The AsyncFileUpload control turns green, indicating that the attachment was successfully uploaded, but the designated method for handling the server side UploadedComplete event is never executed.

"view state" does't work for Image's ImageURL in dynamic controls


Hi all. in my page_load method I call a mthod that it create some dynamic controls. one of them is an Image control that it's ImageURL property set to an URL that is saved in data base. image shows that URL but when postback ocuurs, previous image controls doesn't their image. but other controls for example TextBoxes keep text values. what should I do for keep image url property for this dynamic Images controls?


using __doPostBack with dynamically generated controls


I'm making a page for dynamically handling surveys.  The questions and their related controls (multiple choice, text) are stored in a DB and fed into a page on loading.  For some questions, particular answers will need to disable other questions' controls as they are no longer valid in context.  For example, If the survey asks the user if they've worked in the past year and they respond "No" then I need to disable the choices for the "how much did you earn" question.  The tricky part is that I need to be able to undo this action as well.  If the user now selects "Yes" to the first question, I have to re-enable all the earnings choices.

There are too many controls to always trigger an event whenever something is clicked, so I'd like to limit my postbacks to only those option which can cause a skip to occur.  This becomes a problem for Radio Buttons and DropDown Lists, as I only want the selection/deselection of particular options to cause postback and the others to do nothing (though selection of such an "inert" option will cause postback if it causes the deselection of a skip-causing control).  Not having an equivalent "CheckedChanged" event for Radio Buttons as there is for Checkboxes is irritating.

My solution thus far (for Radio Buttons) is to add t

change attrib value in java script in dynamically generated controls


Hi all,

i use the below code to dynamically generate two dropdowns and a text box in my MVC project.

countValidate is used to concatenate and produce controls with postfix 1 ,2,3 etc.

now i need to access the Criteria? series dropdown and check their values and according to the values received on changing the Criteria dropdown the value textbox must be disabled or enabled, in javascript.

<% countValidate = 1;

<% foreach (var item in Model.ContactSearchCriteria)
               { %>
            <table width="100%">
                    <td width="30%">
                        <%= Html.DropDownList("Field" + countValidate, ViewData["SRFLD" + countValidate] as SelectList, "Select", new { @class = "selectTr

layout of controls added programmatically


hi guys,

I have a custom user control which consists of a placeholder and some buttons.

In this control i add x amount of labels, checkboxes, textboxes etc programmatically at the onload stage.

Problem is these controls that i add are being placed next to each other and wrap like text in a paragraph.

How can i control the layout of these controls so (for example) i only have 2 per line or 4 per line or make sure they are padded correctly.

Sorry for the simple question but i'm new to asp but learning very quickly.

programmatically set hyperlink state in code behind of a web user control


I am writing a web user control that is basically a vertical single level menu.  The layout would look like this:

<asp:Table ID="myTable" runat="server">
            <asp:HyperLink>Menu Choice</asp:HyperLink>  /* which would resolve to the following line.
            <a onclick="__doPostBack('theUniqueIdOfTheUserControl','myArguments');">Menu choice</a>
    . . . etc.

However, I am externalizing the layout to an XML file and am building the table content dynamically.  The source view of the ascx actually looks like this:

<asp:Table ID="myTable" runat="server">

In the Page_Load of the code behind, I read and parse the XML file and save all the pertinent data in the viewstate on the first load.  On all loads including postbacks, I create the rows, cells, and hyperlinks from the viewstate so I don't have to parse the XML file on every postback.

The XML file also specifies CssClasse

User controls and their state?


Hi everyone,

I'm new to ASP.NET and have a question about a user/web control's state...

I have usercontrol that contains a listbox with predefined items. I click a button and it adds that item to a dropdownlist. When I change the dropdownlist item, it does a postback (i have autopostback enabled). Each time i add another item to the dropdownlist, it remembers all of its items!

If I add a public property (with a private field to store) of a list, every postback, this list is then empty.

Why are controls treated differently to properties? How do I store the property values if they keep clearing?

Thank you in advance,

Jaclyn (very confused!)

Source code below.

///Code behind
Partial Class uc_WebUserControl
    Inherits System.Web.UI.UserControl

    Public manualList As New Generic.List(Of String)

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

        Label2.Text += "Load"
        For Each i As String In manualList
            Label2.Text += i
        For Each i As ListItem In DropDownList1.Items
            Label2.Text += i.Text
        Label2.Text += "Load"
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Binding WPF Controls to an Entity Data Model

In this interview, programming writer, McLean Schofield, demonstrates how to bind WPF controls to an entity data model, using Visual Studio 2010 Beta 1. You can also learn more in the topic: Walkthrough: Binding WPF Controls to an Entity Data Model.

Custom Controls in C# .NET

Embedding user controls in a Windows form is just like adding a simple button or text box that are already provided with .NET. These basic controls were written essentially like you code your own controls. Typically the controls you design are to be used in multiple forms or to modularize your code. These reasons help reduce the amount of code you have to type as well as make it easier for you to change your implementation. There should almost never be any reason to duplicate code because it leaves a lot of room for bugs. So, implementing functionality specific to your control in the control's source code is a good idea. This reduces code duplication as well as modularize your code, which is a good programming guideline.

Truly Understanding View State

This article provides a detailed understanding of the ViewState.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend