Control Building and ViewState Lesson for the Day

Control Building and ViewState Lesson for the Day

Whenever I am working on a problem and hit a perplexing roadblock that impedes my process, my initial emotional state is calm.  “I'll figure out this problem soon,” I tell myself, as I explore workarounds or examine the code base to try to understand why I can't do what I know I should be able to do.  If this search goes on for five or more minutes, I start to get a little flustered.  Off to Google!” I declare, hoping there has been some other unfortunate soul who has experienced the same problem and has shared his solution.  I usually hit the Google Web search first and, if I have no luck there, I delve into the USENET postings on Google Groups.  If 15 minutes have passed with no hits from Google, I start to get angry at myself.  “I SHOULD KNOW HOW TO FIX THIS,” I say, as I pour back over the material I examined in the first five minutes, knowing there must be somethinig I overlooked.  What's interesting is that if this search continues into, say, the half hour mark, my emotions start to sway from frustration and despair to glee.  “Wait until I figure out what went wrong,” I reason, “and I can share it on my blog, and it will help others down the road.”  And that's what keeps me going.

Today's lesson - which will hopefully save you the 40 minutes it cost me - centers around composite controls, the DropDownList Web control, and ViewState.  Let's say you want to create a composite control that contains a DropDownList that already is bound to database data (namely, it does not allow the control developer to specify the DropDownList's DataSource as would normally be the case: for a discussion on the pros and cons of this approach check out Composite Controls That Do Their Own DataBinding by Andy Smith).  If you are at all like me, you're composite control's code would look like this (WARNING: this is wrong):

public class MyControl : WebControl, INamingContainer
{
  ...

  protected override void CreateChildControls()
  {
    DropDownList ddl = new DropDownList();
    if (!Page.IsPostBack)
      // do data binding to some database...

    Controls.Add(ddl);
  }
}

This, as aforementioned is the WRONG WAY to do it.  Why?  Well, give the control a whirl by creating an ASP.NET Web page with this control and a Button Web control.  When you visit the page the first time, the DropDownList is displayed, populated with the database data.  However, if you click the Button and the page posts back, the items in the DropDownList disappear - the DropDownList is not saving its view state.

If you're like me, the first thing you do is crack open Developing Microsoft ASP.NET Server Controls and Components, thumb through to Chapter 12: Composite Controls, and read the section titled “State and Child Controls.”  The gist of the section says that composite controls don't need to employ extra effort to save the view state of their children since it's saved automatically when the page recursively walks the control tree to generate the entire view state.  Opening Reflector, I poured through the Page and Control classes, and saw that, yes, the control hierarchy should be walked and the view state saved, so when my composite control's SaveViewState() method was called, it should save not only its own view state, but the view state of its child(ren): namely, the DropDownList.  But, evidently it was not.

This got me to scratching my head.  Why isn't the DropDownList's view state being saved?  EnableViewState for both the Web page, composite control, and DropDownList were all set to True (the default).  I looked at the SaveViewState() method for the DropDownList and confirmed that it should be saving its view state.  So why wouldn't the DropDownList be saving its view state?

And then it occurred to me - check to make sure that the DropDownList's IsTrackingViewState property is True - if it isn't, then the DropDownList won't be recording changes to its state, and therefore won't produce a ViewState.  A control begins tracking its view state when its TrackViewState() method is called, and this is handled after the Initialization stage of the page lifecycle.  So, if the DropDownList is being added after that stage, then it wouldn't be tracking its view state, and therefore its state would be lost on postbacks.

But wait a minute, if you add a child control via the Controls.Add() method, the added child control's TrackViewState() method is automatically called.  But wait!  Only those items added to the view state after the view state has started being tracked will be recorded.  So binding the items to the DropDownList prior to adding the DropDownList to the Controls collection causes those additions to not be saved in the view state for the DropDownList.  Rather, we need to first add the DropDownList to the Controls collection and then bind the database data to the list.  The order matters because we don't want to bind the data to the DropDownList until after we've started tracking view state.

To summarize, the correct code should look like:

public class MyControl : WebControl, INamingContainer
{
  ...

  protected override void CreateChildControls()
  {
    DropDownList ddl = new DropDownList();
    Controls.Add(ddl);   // Add the control FIRST

    if (!Page.IsPostBack)  // Bind data AFTER
      // do data binding to some database...
  }
}

Partial credit goes to (IIRC) Alex Lowe.  If I'm remembering correctly, way back in (yikes!) 2001 he tech reviewed ASP.NET: Tips, Tutorials, and Code for which I authored some chapters, and on one of the chapters I had an example of adding dynamic controls to a page and - again, if my memory doesn't fail me - he noted that you wanted to first add the control to the page prior to setting properties that needed to be maintained in the view state.

posted on Wednesday, October 06, 2004 3:17 PM

href="http://scottonwriting.net/sowblog/Services/Pingback.aspx" rel="pingback">

Feedback

# RE: Control Building and ViewState Lesson for the Day 10/6/2004 4:42 PM nospamplease75@yahoo.com (Haacked)

Nice tip. And I feel you on the problem solving process. Sometimes I bang my head against the monitor as a step after google group searches and before poring over the material again.

# ViewState and Composite Controls: Problem Solved! 10/6/2004 8:47 PM Joel's Virtual Desktop

# ViewState With Dynamic Composite Controls 10/6/2004 8:53 PM Joel Ross

# re: Control Building and ViewState Lesson for the Day 10/6/2004 10:47 PM Wessam Zeidan

Hi Scott,
this is exactly what I was trying to tell you regarding adding dynamic controls at page load event. If we want to save the properties of a dynamicaly added control in the viewstate, we need to add the control to the controls collection first and then set its properties.

# Composite Controls and Viewstate 10/7/2004 6:39 AM Extemporaneous Mumblings

# Composite Controls and Viewstate 10/7/2004 6:40 AM Extemporaneous Mumblings

# re: Control Building and ViewState Lesson for the Day 10/7/2004 11:04 AM Milan Negovan

All righty, let's see... 40 minutes multiplied by... What's your hourly rate? And who do I make it payable to?

# Control Building and ViewState Redux 10/8/2004 8:36 AM Scott on Writing

# Composite Controls and ViewState 10/10/2004 5:33 PM OdeToCode Link Blog

# re: Control Building and ViewState Lesson for the Day 10/27/2004 10:15 AM Steve McGinnis

Sometimes I want to create a control, set properties, and use methods of the control, and then decide to add to the control tree or not.
In my own controls I make sure TrackViewState has been called before storing anything in ViewState. The problem with the built in controls is TrackViewState is virtual so it can only be called by a derived class. So if you want to be able to call TrackViewState you must inherit from the control.

Here is the code for an inherited TextBox.

public class tb : System.Web.UI.WebControls.TextBox
{
public void BeginTrackingViewState()
{
this.TrackViewState();
}
}

Using tb you can call BeginTrackingViewState before setting any properties that use viewstate and you don't have to add to the control tree first.

# re: Control Building and ViewState Lesson for the Day 10/28/2004 11:03 AM Sean Kuehnel

Good read. I found myself in the same boat on this one sept on step 1 on our problem solving: googling. google almost never lets you down these days.

# re: Control Building and ViewState Lesson for the Day 11/1/2004 2:01 AM Zubair Ahmed

Hi,

I have a Datagrid, where I am dynamically creating a textbox control into one of the datagrid columns through its ItemDataBound property.

If e.Item.ItemType = System.Web.UI.WebControls.ListItemType.Item Or e.Item.ItemType = System.Web.UI.WebControls.ListItemType.AlternatingItem Then
Dim mytb As New TextBox
e.Item.Cells(3).Controls.Add(mytb)
End If

Now when the datagrid is paged or postedback, the data within the textbox is lost.

I need to know where should I load these controls' viewstate and how?

# re: Control Building and ViewState Lesson for the Day 11/5/2004 1:57 AM Christie Gibbs

Hi there,

What about dynamically loading a usercontrol after somebody has clicked a button in a page. From the page_load i call a function "CreateControl()" that loads this control (LoadControl()). After that i populate the properties of this loaded control. Then i add it to a panel. From preventing the usercontrol from dissapearing after postback, i call CreateControl on each page_load. The data entered will be remembered nicely, i dont have to do anything extra...or is it because its a usercontrol instead of any other webcontrol ?? I wonder....

# Retrieving viewstate values from dyamically created server controls within a composite server control (SQL Reporting Services parameter control) 12/8/2004 3:30 PM Josh Robinson's WebLog

# re: Control Building and ViewState Lesson for the Day 1/20/2005 10:31 AM MB

Article and tips was very usefule. I have an issue:

I am creating a dynamic droplist and recreating it during postback with same control ID. ASP.NET automatically updates the properties and items in postbacks. Only selecteditem is not getting updated in postbacks. Do I need to do something for this?

# re: Control Building and ViewState Lesson for the Day 1/26/2005 3:32 AM Pete Midgley

Conversely, I'm creating a page that builds a dynamic dropdown-type questionnaire from parameter tables, and on user selection of an identifier, populates the dropdowns' selectedindex from any existing saved answers on database. So far so good.
Then I change identifier, and the questionnaire redisplays, and all the previous answer settings carry over from before. I think viewstate needs clearing between instances of the questionnaire. Apart from walking the dynamic controls resetting their selectedindices, is there a 'forget viewstate' I can run as the user changes the survey identifier?

# re: Control Building and ViewState Lesson for the Day 1/26/2005 6:32 PM Edijer Sarmiento

Lifesaver!

# re: Control Building and ViewState Lesson for the Day 1/30/2005 10:54 AM visitor1

i add a dynamic control button in repeater
and the itemDataCommand - not fire to the click event.

do u have example for this?
,
10x ahead.

# re: Control Building and ViewState Lesson for the Day 1/30/2005 10:59 AM visitor1 opps i forgot something

instead: itemDataCommand
it should be: ItemCommand

and another thing - i add the dynamic control
in the ItemDataBound event of the repeater.

# re: Control Building and ViewState Lesson for the Day 2/1/2005 9:19 AM JoJo

I'm having a similar problem to the last guy, i'm creating a control button, but when I click the new button it just disapears

# re: Control Building and ViewState Lesson for the Day 2/1/2005 9:31 AM Scott Mitchell

When working with dynamic controls it is imperative that you rebuild the control hierarchy EVERY POSTBACK. Are you sure that with the Repeater you are rebinding the data to the Repeater (i.e., setting the DataSource property and calling the DataBind() method) on each and EVERY postback? If not, this is why you're button is disappearing, because it's not being recreated on postback!

# re: Control Building and ViewState Lesson for the Day 2/4/2005 12:21 PM Chris F

Here's a strange one for you.

I have a page where I add 4 user controls during the page_init stage. Everything works fine.

When a user clicks on a button in one user control, I add a couple of controls (textbox and button) using Parent.Controls.Add(b). This works fine. I check to see if the text from the text box is available during Page_Load, and do some stuff with it. This works fine.

However, if I change it to Parent.Controls.AddAt(0,b) then a DDL in another usercontrol loses its state when button b is clicked! (Viewstate information is preserved, according to the Trace output, and it's the only control in any of the user controls that has view state enabled.)

The data for the DDL is created the first time the UC is loaded:

Dim atypes As New ListItemCollection
...add some ListItems...
ddlAddresses.DataSource = atypes
ddlAddresses.DataTextField = "text"
ddlAddresses.DataValueField = "value"
ddlAddresses.DataBind()
ddlAddresses.SelectedValue = selected
ddlAddresses.Visible = True

Any clues where I could start looking? I'm stumped.

# re: Control Building and ViewState Lesson for the Day 2/4/2005 12:38 PM Brad Teague

I'm having the same issue that "Pete Midgley" above is having. I have a treeview control from which a user selects which form they need to fill out, and then based upon their selection, I dynamically create the form from properties stored in a database. All good. If we do post backs related to that form... again, all good. Now, if they select a NEW form to load, I go through the process of

1) panel.controls.clear()
2) rebuild new form
3) populate panel with new form
4) populate starting data for new form

The issue is that it is loading the saved viewstate information for the prior form in the current one. For instance, form-A has 2 textboxes, and form-B has 4 textboxes. form-A loads first, the user fills out both boxes. There is a postback done to submit the data. Data is saved. User selects form-B. form-B is loaded and the first 2 textboxes of form-B will have the data from form-A loaded into them.

Does this make sense? Any ideas?

# re: Control Building and ViewState Lesson for the Day 2/4/2005 2:06 PM Brad Teague

I think I might have found the answer to my own question. I thought I would pass it along so that anyone else that gets to this point might also use the solution.


I found that if I disabled viewstate on the parent "container/placeholder" control I got the results I was looking for. This, along with the order I have listed above for a postback process seems to work.
Namely, do the parent.controls.clear() before you populate your parent with the new controls and make sure your parent's "EnableViewState" property is set to false.



# re: Control Building and ViewState Lesson for the Day 2/14/2005 1:45 PM Ryan Hefner

Hey,

I have been working on a form that generates dynamic controls via a database. Everything seems to be working just fine, up until the time that I attempt to submit the form for insertion into the database. For some reason, I cannot seem to reference the dynamic controls on the page, but do see there values represented within the "Form Collection" area of the page trace. Does anyone know if there's a way to reference the Form Collection values directly. That seems to be the only way in which to get the values for insertion.

Thanks,
Ryan

# re: Control Building and ViewState Lesson for the Day 3/4/2005 12:56 AM Mattias

I use ASP.NET 2.0 and add controls in the OnInit-method. However, the VIEWSTATE still includes all my settings and gets very big.

What am I doing wrong?

Thanks,

Mattias

public partial class DataGrid1_aspx
{
// protected override void CreateChildControls()
protected override void OnInit(/* object sender, */ EventArgs e)
{
// + Columns {System.Web.UI.WebControls.DataControlFieldCollection} System.Web.UI.WebControls.DataControlFieldCollection


this.GridView1.AutoGenerateColumns = false;

// this.GridView1.Columns.Clear();

BoundField field1;

// temp kludge, since setting to false made that the value wasn't sent to update
// this.GridView1.DataKeyNames = new string[] { "Id" };
// this.GridView1.DataKeys = "Id";
field1 = new BoundField();
field1.DataField = "Id";
field1.HeaderText = "Id";
field1.Visible = true;
// field1.ReadOnly = true; then it isn't sent
this.GridView1.Columns.Add(field1);


field1 = new BoundField();
field1.SortExpression = "Age";
field1.DataField = "Age";
field1.HeaderText = "Ålder";

this.GridView1.Columns.Add(field1);

field1 = new BoundField();
field1.SortExpression = "Name";
field1.DataField = "Name";
field1.HeaderText = "Namn";

this.GridView1.Columns.Add(field1);

field1 = new BoundField();
field1.SortExpression = "Address1";
field1.DataField = "Address1";
field1.HeaderText = "Adress rad 1";

this.GridView1.Columns.Add(field1);

// this.GridView1.Sorting = false; detta är ett Event!
this.GridView1.AllowPaging = true;
this.GridView1.AllowSorting = true;
// this.GridView1.SortExpression = "Name"; READONLY
this.GridView1.AutoGenerateEditButton = true;

// ObjectDataSource1.TypeName = "datagridlib.EmployeeManager";
// ObjectDataSource1.UpdateMethod = "UpdateEmployee";

this.EnableViewState = true; // needed for update since I add a lot of BoundFields.

base.OnInit(e);

}

# re: Control Building and ViewState Lesson for the Day 4/6/2005 12:19 PM Lisa

Your article seemed very helpful. But what if the user wants to add items to a listbox's item collection in design view (for instance). I'm trying to write a control that has two listboxes in it. I exposed the listboxes as properties and dragged the composite control onto a webpage. I was able to add items to the items collection of each listbox, but when I tried running the page, it reinstantiated the listboxes, and the collections reverted to empty.

Here's the code:

Option Strict On
Imports System
Imports System.ComponentModel
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.IO

<DefaultProperty("SelectedIndex"), Description("A List2List control that uses ListBox"), ToolboxData("<{0}:PickList runat=server></{0}:PickList>"), ParseChildren(True), PersistChildren(True)> _
Public Class PickList
Inherits System.Web.UI.WebControls.WebControl
Implements INamingContainer

Private _LeftList As ListBox
Private _RightList As ListBox
Private _MoveLeft As Button
Private _MoveRight As Button

Private Sub PickList_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init
_LeftList = New ListBox
_RightList = New ListBox
_MoveLeft = New Button
_MoveRight = New Button
End Sub

Private Sub PickList_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox("hi")
End Sub

Private Sub PickList_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
MsgBox("hi")
End Sub

Public Sub New()
MsgBox("hi")
End Sub

Protected Overrides Sub CreateChildControls()

Controls.Clear()

_LeftList.ID = "LeftList"

_RightList.ID = "RightList"

_MoveLeft.ID = "MoveList"
_MoveLeft.Width = Unit.Pixel(25)
_MoveLeft.Font.Name = "wingdings"
_MoveLeft.Text = "×"

_MoveRight.ID = "MoveRight"
_MoveRight.Width = Unit.Pixel(25)
_MoveRight.Font.Name = "wingdings"
_MoveRight.Text = "Ø"

Controls.Add(_LeftList)
Controls.Add(_RightList)
Controls.Add(_MoveLeft)
Controls.Add(_MoveRight)

End Sub 'CreateChildControls

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

EnsureChildControls()
AddAttributesToRender(writer)

writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0")
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0")
writer.AddStyleAttribute("display", "inline")
writer.RenderBeginTag(HtmlTextWriterTag.Table)
writer.RenderBeginTag(HtmlTextWriterTag.Tr)

writer.RenderBeginTag(HtmlTextWriterTag.Td)
_LeftList.RenderControl(writer)
writer.RenderEndTag() 'td

writer.RenderBeginTag(HtmlTextWriterTag.Td)
_MoveLeft.RenderControl(writer)
_MoveRight.RenderControl(writer)
writer.RenderEndTag() 'td

writer.RenderBeginTag(HtmlTextWriterTag.Td)
_RightList.RenderControl(writer)
writer.RenderEndTag() 'td

writer.RenderEndTag() 'tr
writer.RenderEndTag() 'table

End Sub 'Render

#Region "Child controls exposed fully as properties"

Public Overrides ReadOnly Property Controls() As System.Web.UI.ControlCollection
Get
EnsureChildControls()
Return MyBase.Controls
End Get
End Property 'Controls

<Category("Child Controls"), Bindable(False), NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
Public ReadOnly Property LeftList() As ListBox
Get
Me.EnsureChildControls()
Return _LeftList
End Get
End Property 'LeftList

<Category("Child Controls"), Bindable(False), NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
Public ReadOnly Property RightList() As ListBox
Get
Me.EnsureChildControls()
Return _RightList
End Get
End Property 'RightList

<Category("Child Controls"), Bindable(False), NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
Public ReadOnly Property MoveLeft() As Button
Get
Me.EnsureChildControls()
Return _MoveLeft
End Get
End Property 'MoveLeft

<Category("Child Controls"), Bindable(False), NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
Public ReadOnly Property MoveRight() As Button
Get
Me.EnsureChildControls()
Return _MoveRight
End Get
End Property 'MoveRight

#End Region

End Class

# re: Control Building and ViewState Lesson for the Day 4/12/2005 4:18 PM toxaq

[GT Vice City]You the mang mang![/GT Vice City]

Thank you so much for this. I had bitten off rather alot trying to build a beautiful composite control that would bind and display my business object. In theory it was great but this one had me done for a whole day!

# 创建动态数据输入用户界面 4/15/2005 9:35 AM yicko

Ping Back??:blog.csdn.net

# re: Control Building and ViewState Lesson for the Day 5/26/2005 4:23 AM J

Hi,
Many Many Many Thanks. funny followed very similar path and got very close.

# re: Control Building and ViewState Lesson for the Day 8/16/2005 1:43 PM Daniel

Oh lordy you saved me like a millions hours... well I only wasted a few, but that really saved the day... thanks man!!!

# re: Control Building and ViewState Lesson for the Day 8/24/2005 9:20 AM Will

Sadly, the most frustrating part is that the framework documentation, samples and tutorials don't point these little nuances out. Oh sure, you could spend $60 on a book but after spending $1000 on VS.NET, should you need to?

# re: Control Building and ViewState Lesson for the Day 9/7/2005 8:02 AM PEDRO GALLARDO

Hi friends

Maybe any of you can help me with a problem related to dynamic controls that is making me crazy. Here below you can find the relevant code, which is simple, as I am not a very advanced developer.

As you can see, I am always loading just ONE user control, but it is dynamical because, depending of the selection made by the user in a dropdown list, it will load the control out of a path or other. The difference is not in the paths, but also in the properties an child controls of the different controls.

I obtain the much hatred message that you can figure out: "Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. "

What is making me a broken man is that I can not guess the pattern in which this message appears. I am changing the selections in the dropdownlist, causing postbacks at whish, without doing anything else, but the error appears when it is not expected, when it wants, I could say, and that's the reason why I can not see the cause-effect relationship.

As I hope it is not a hard to resolve them, your help will be much appreciated. Yo can reach me at pagmpro@yahoo.es.

Thank you very much for your attention.



#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
instanciapanel()
End Sub


'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load



End Sub

Private Sub instanciapanel()

recursotipo = Request.Form("txtvalor")

If recursotipo = "" Then
recursotipo = "1"
srecursotipo = "articulo"
Else
srecursotipo = Request.Form("txttexto")
End If

Me.agregacontrol("recurso")

End Sub

Private Function agregacontrol(ByVal idelemento As String)


Dim dvelemento As New HtmlGenericControl
dvelemento.ID = "dv" + idelemento.ToString
pncontenido.Controls.Add(dvelemento)

Dim ctl As Control


Select Case idelemento
Case "recurso"
ctl = LoadControl("../controles/uc" + comunes.quitaacentos(srecursotipo.ToString) + ".ascx")
dvelemento.Style.Add("Z-INDEX", "999")

'viewstate("recurso") = ctl
Case "archivo"
ctl = LoadControl("../controles/uc" + comunes.quitaacentos(idelemento.ToString) + ".ascx")
dvelemento.Style.Add("Z-INDEX", "1000")
Case Else
ctl = LoadControl("../controles/uc" + comunes.quitaacentos(idelemento.ToString) + ".ascx")
dvelemento.Style.Add("Z-INDEX", "1")

End Select

ctl.ID = "uc" + idelemento.ToString
Page.FindControl(dvelemento.ID.ToString).Controls.Add(ctl)


End Function

# re: Control Building and ViewState Lesson for the Day 10/24/2005 1:12 PM Atul Bahl

Can any body help...

I have a custom control drived out of datagrid control, which I am using in a user control.

Based on certain events this usercontrol which in turn has custom grid is loaded dynamically.

When I am trying to sorting or any postback event on the custom data grid my post back page does not loads the control.

I have tried everything like you guys have mentioned but it is not working.

Do I have to implement IPostBackEventHandler inside the custom grid? Or what is missing....

Thanks in advance

Atul

# re: Control Building and ViewState Lesson for the Day 11/15/2005 5:48 AM tticom

Excellent article, almost solves my problem.
My control is being created properly but without the selectedIndex being set. Have you any advice for me?

# Guidelines for Dynamically Loaded Controls 11/20/2005 7:19 PM Nick Harrison

# re: Control Building and ViewState Lesson for the Day 11/24/2005 12:24 AM David Wang

Different controls may handle ViewState differently. For example, "both the ListBox control and the DropDownList control automatically store the items you add to them at run time. The Table control, however, will automatically store data only for the table cells created at design time in the Collection Editor. To create additional table rows and cells at run time, you need to rebuild the table from information stored in a state variable" (Developing Web Applications with Microsoft Visual Basic .NET 2nd ed)

# re: Control Building and ViewState Lesson for the Day 12/8/2005 9:38 PM Parveen

The problem which i am facing is:

I want to add a dropdownlist on click of a button and not at page load. for this i declare and instantiate Dropdownlist object at button click event and add to the control hierarchy and then add listitem to the dynamic dropdownlist. Now if a postbact happens i dun find the control itself on the page. What can be the reason??







# 创建动态数据输入用户界面 1/17/2006 6:19 PM godwood

???????? Web ???,Web ??????????????????????????????????????????????? Web ???????????????????????????,?,??????????????????????,?????????? Web ??,?????????????????????????????

# You rock! 1/21/2006 11:25 PM Jeff Dean

Your threshold is 5 minutes - mine seems to be about 4 days - but you really saved me on this one. I never would have come to this on my own.

Thanks!

# re: Control Building and ViewState Lesson for the Day 1/23/2006 11:33 AM Radhika

Hi All,
I am trying to add htmlinputfile controls dynamically on the click of a button..ie on every button_click event I should add a new htmlinputfile control to the already existing htmlinputfile controls.
but..every time its only adding the control once ..on later on button clicks it is not adding any more controls....

please help
Thanks in advance.

# Custom Controls e ViewState 1/24/2006 7:49 AM FoxyBlog

# Custom Controls e ViewState 1/24/2006 7:51 AM FoxyBlog

# re: Control Building and ViewState Lesson for the Day 1/25/2006 8:19 AM Satish

Gods do grant wishes... Thanks a lot man.. Had the same issue but I was binding data from my aspx page. So raised a Event after the control.add() method in the Custom control and handled the Event in my aspx pages to bind the data to the dropdown. Thanks a lot again.

# re: Control Building and ViewState Lesson for the Day 2/3/2006 6:42 AM antoipepper

Hi Scott,
I created a composite control that contains a radiobuttonlist and is bound to a database at runtime.
The radiobuttonlist is populated only at runtime and it saves its view state.
Here's the problem, I put it into the item template of a datalist control and when i try to get the selected value of each radiobuttonlist, it returns only the value for the first radiobuttonlist. The others return nothing.
I'm a little confused because the viewstate of all the radiobuttonlists are saved so after postback i can see user selection but i can't extract the selected valued for any but the first.
What can be the reason?

# Dynamic PlaceHolder with RadiobuttonList and DropdownList 3/20/2006 5:29 AM Meghna

Hi Mr.Scott,

In my case,Placeholder is having default radiobuttonlist and on selection of it,actions are being fetched from DB and new radiobuttionlist is formed and displayed instead of them and on selection of any of them,attributes are being fetched from DB and dropdownlist are being added and displayed along with second time generated radiobuttonlist.
But when i submit the form with value selected in dropdownlist and runs thru the placeholder,only the two first radiobuttonlist,added in html is there and no other control is there.I have added the control to the placeholder first and then set the properties.
What else can be the reason and how to get the controls that got added programatically?

Awaiting reply.

Regards,
Meghna.

# re: Control Building and ViewState Lesson for the Day 4/5/2006 11:53 PM rpjmenez

I make a table with textbox in each cell, the first time the table is created dynamically reading data from a database, the the user can change the data stored in the textboxs but wheen the user click on button save, the data within the textbox is lost.

I need to know where should I load these controls' viewstate and how?

# re: Control Building and ViewState Lesson for the Day 5/11/2006 11:22 PM Sri

Hi,
I am Adding few textboxes controls to DataGrid in ItemDataBound Event.
After creating controls , I set the control values from data base and add it to data grid.

I am doing the above process during postback also.

Event though i am setting values in itemdatabound event , controls are persisting with posted values i.e. overrides my data base values(which i have set during data bound event) with posted values.

Can any one help out on this?

# re: Control Building and ViewState Lesson for the Day 6/7/2006 9:10 AM Jagan

I have similar but different problem. I have to create dynamic controls on the user selection of a drop down list event. By the time this happens all the initialization done and eventhough I create the controls in the DDList selected event, my dynamic controls are disappearing in the post back. Does anyone know solution for this kind of requirement? I appreciate your help.

# re: Control Building and ViewState Lesson for the Day 8/2/2006 7:40 AM tobias

Hi,
i am still very confused about all this:

Why is it working with the DropDownList and ListItems?

Why is it NOT working with a HtmlTable and HtmlTableRow and/or HtmlTableCell. I even use the "special" properties/methods .Rows.Add(), .Cells.Add() and not the .Controls.Add()!

I tried to understand all this nearly the whole day without success. Please help.

Btw i want to finish my file system browser usercontrol that should show up a directory like an ftp client on an aspx page - the rows (cells) are beeing added on each page request within the Init. The folder names are shown as LinkButtons with command eventhandler. within the eventhandler i .Clear() the HtmlTable and add rows, cells according to the clicked LinkButton/Link. But if i try to get even one subfolder deeper it isn't working.

I already tried to set a ViewState entry explicitly in the event handler but it is NULL in the Init because the LoadState is after the Init.

# 创建动态数据输入用户界面 8/30/2006 7:03 PM zlz_212

???????? Web ???,Web ??????????????????????????????????????????????? Web ???????????????????????????,?,??????????????????????,?????????? Web ??,?????????????????????????????

?????????????,?????????????????????,??????????????????,?????????????,????????????,???????...

# re: Control Building and ViewState Lesson for the Day 9/3/2006 4:20 AM supNate

Hi,
when does the LostPostData been invoked when added a control during the load precedure?

# re: Control Building and ViewState Lesson for the Day 11/29/2006 5:27 AM Ruben Cordoba

Given a LinkButton inside a dynamic user control loaded inside a GridView row template, I see LinkButton_Command is never fired. Why?

# Persistenza del viewstate nei controlli di tipo CompositeDataBound 7/25/2007 11:59 PM Luke's Blog

# Persistenza del viewstate nei controlli di tipo CompositeDataBound 7/26/2007 11:36 PM Luke's Blog

# Extended DropDownLists 10/30/2007 8:21 AM Andy Potts

Oh my gawd! I owe you two beers!
I've been banging my head for over an hour and a half.

Anyway, my problem was similar. It wasn't a composite control, but a control derived from dropdownlist.

public class MyAutoLoadingList : DropDownList
{
protected override void OnInit(EventArgs e)
{
if (! IsPostBack)
{
if (cachedData)
{
LoadFromCache();
}
else
{
LoadFromDatabase();
}
}
}
}

I could have loaded from the cache on postback, but wanted implementors to add additional items which would then be saved to the ViewState.
Anyway, no items were being saved to the ViewState.

You mentioned a magic line: TrackViewState().

I was initialising the control in OnInit (as you should - it is better than onLoad because of ViewState and Postback reasons).

But the trick is that OnInit for a CONTROL occurs before OnInit for a PAGE. And as you said, the TrackViewState is called in the Page Initialisation.

So, I modified my code to manually call TrackViewState.....

public class MyAutoLoadingList : DropDownList
{
protected override void OnInit(EventArgs e)
{
this.TrackViewState();

if (! IsPostBack)
{
if (cachedData)
{
LoadFromCache();
}
else
{
LoadFromDatabase();
}
}
}
}

and then it worked! Thank you very much!

# re: Control Building and ViewState Lesson for the Day 12/8/2007 8:11 AM Mahi

Hi Scott,

I got a problem with View state of a Datagrid. The exact scenario is:

I have a page where I instantiate many user controls dynamically. One of the user controls got a Datagrid. When I first display the page, the datagrid is displayed with out any issue. If i do any post back on the page, the datagrid is no longer visible. I am pretty sure, it is because the view state of the data grid is not saved and i am not sure why it is not saving the view state of the datagrid.

I have checked for the following by debugging the code:

When the datagrid is instantiated, I have checked for the following:

• EnableViewState property is set to true
• TrackViewState property is also set to true
• The user control and the datagrid in it is instantiated on every post back
• While instantiating it on a post back, if I data bind the grid, the grid will be seen but the changes made to the controls in the grid will be lost.


The user control that holds this datagrid also holds few other controls like textbox etc and there is no problem with the view state of those controls:

Any help is highly appreciated.

Let me know if i can provide more info.

Regards
Mahi.

# re: Control Building and ViewState Lesson for the Day 12/8/2007 8:14 AM Mahi

Hi Scott,

I got a problem with View state of a Datagrid. The exact scenario is:

I have a page where I instantiate many user controls dynamically. One of the user controls got a Datagrid. When I first display the page, the datagrid is displayed with out any issue. If i do any post back on the page, the datagrid is no longer visible. I am pretty sure, it is because the view state of the data grid is not saved and i am not sure why it is not saving the view state of the datagrid.

I have checked for the following by debugging the code:

When the datagrid is instantiated, I have checked for the following:

• EnableViewState property is set to true
• TrackViewState property is also set to true
• The user control and the datagrid in it is instantiated on every post back on page init of the page
• While instantiating it on a post back on page init of a page, if I data bind the grid, the grid will be seen but the changes made to the controls in the grid will be lost.


The user control that holds this datagrid also holds few other controls like textbox etc and there is no problem with the view state of those controls:

Any help is highly appreciated.

Let me know if i can provide more info.

Regards
Mahi.

# 创建动态数据输入用户界面 2/14/2008 4:33 AM 伦惠峰

# getting values in dropdownlist without postback from server 7/18/2008 5:30 AM Mahesh

We have a dropdownlist inthat we have 3 names ..................ex. Mahesh,suresh,rahul like this



If we select the any name we have to display its age from server..........it shud go to server and fetch the data ....this is very normal process.........





Here is my query is





For the first time of the load itself we have to get ages from the server for all the 3 members........i.e mean again if I select any



name from the list post back shud not be done.......i.e we shud not display the progress bar..........

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值