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

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

Custom control's children do not persist contents after postback

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

I have created a really simple custom control to render panels into a page.  The code is below.  When I use my control and add any webcontrol to it, after each page postback the contents of these child controls vanishes.

I must have missed something really simple but please run the example to reproduce this.  Can anyone please enlighten me as to why the controls are being 'emptied' of their contents, and how I stop this occuring?

Crude diagram

Here is the code for the control

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

<ToolboxData("<{0}:MyTestControl runat=server></{0}:MyTestControl>"), ParseChildren(True)> _
Public Class MyTestControl
	Inherits CompositeControl
	Implements INamingContainer

	<NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
	Public Property Panels() As List(Of Panel)
			Dim s As Object = ViewState("_StaticPanels")
			If s Is Nothing Then
				s = New List(Of Panel)
			End If
			Return CType(s, List(Of Panel))
		End Get
		Set(ByVal value As List(Of Panel))
			ViewState("_StaticPanels") = value
		End Set
	End Property


View Complete Post

More Related Resource Links

unable to trace value after postback within Custom Server Control

public class TextBox : AStateManagement, IControl { #region "Variables" #region "Local Variables" protected System.Web.UI.WebControls.WebControl _TextBox = null; protected string _CssClass = string.Empty; protected string _Text = string.Empty; protected bool _Visible = true; protected bool _Enabled = true; protected string _ID = string.Empty; protected bool _IsViewStateLoaded = false; #endregion "Local Variables" #region "Global Variables" #endregion "Global Variables" #endregion "Variable" #region "Constructor" public TextBox() { _TextBox = new System.Web.UI.WebControls.TextBox(); _TextBox.ID = this.UniqueID; } #endregion "Constructor" #region "Events" #endregion "Events" #region "Disposable" #endregion "Disposable" #region "Properties" public override string CssClass { get { return _CssClass; } set { _TextBox.CssClass = _CssClass = value; } } public virtual string Text { get { return _Text; }

How to Make a custom property or a page persist across postback



As the title suggests, I have an object to hold some specific state information in my web application - I pass it back & forward between pages by making it a property of a basepage which works fine, but I lose it on postback.

Is there any way to persist this property without manually adding & reading it again from viewstate?



Custom Control: Multiple children, "{0} can accept only one child."


Long story short - I'm trying to build a custom accordion control that in essence is a Scroll Viewer wrapped around a Stack Panel.  Once I get past the hump I'm at now which is getting the custom control to accept multiple children I should have no further issues.  


Below is my style for the control:


  <Style TargetType="{x:Type local:ScrollableAccordion}">
    <Setter Property="Template">
        <ControlTemplate TargetType="{x:Type local:ScrollableAccordion}">
          <Border Background="{TemplateBinding Background}"
              BorderBrush="{TemplateBinding BorderBrush}"
              BorderThickness="{TemplateBinding BorderThickness}">
          <ScrollViewer Height="{TemplateBinding Height}"
                 Width="{TemplateBinding Width}"

Custom Control Design-Time SiteMap Provider Error


Greetings - I was referred here by MSDN forums hope this is the right place -  

I have a custom control (:WebControl) that renders web.sitemap in a specific way. While it runs error free and produces the expected result, at Design-Time it complains

Error Creating Control - MyControl  The provider 'AspNetXmlSiteMapProvider' specified for the defaultProvider does not exist in the providers collection.

I have discovered that the error is cause by this line of code:

string div = string.Format("<div class='{0}' id='{1}'>{2}</div>", this.CssClass, this.ID.ToString(), EnumerateNodesRecursive(SiteMap.RootNode, level));

or more specifically, by the reference to SiteMap.RootNode - I am not clear what is missing thoough because I have configured the SiteMapProvider in web.config as this:

        <add name="AspNetXmlSiteMapProvider" 
             type="System.Web.XmlSiteMapProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 

video tutorial link for composite and rendered custom server control


hii all

i am new to technology so go easy on this post

according to what i read from web there are 3 type of custom server controls

1 superclass

2 composite

3 rendered

i found video tutorial for superclass custom server control but couldnt find video tutials for other 2.

please forward me link for composite and rendered custom server controls video tutorial  

image inside custom server control



I want to use an image inside a Custom Web server control ! 

Do I need to use Web.resources ? if so , how to do ?

Custom Server Control Property not maintaining state


I have created a server control consisting of a TextArea and a div under it.  My goal is to create my own asp:TextArea type control.  the div is for a Character count of the text area and seems to work ok but i added a CharacterCountVisible property to the control that is always returning true.  See Proptery definition below


<Bindable(False), Category("Appearance"), DefaultValue("True"), Localizable(True)> Property CharacterCountVisible() As Boolean
        Return _CountBoxVisible
    End Get
    Set(ByVal value As Boolean)
        _CountBoxVisible = value
    End Set
End Property

Note the _CountBoxVisible variable is define inside the class as :

Dim _CountBoxVisible as Boolean = True

What I am trying to do is give the user/coder the option to show/utilize the char count feature.  Can make it disappear with textarea1.CharacterCountVisible = False but setting it to true will not make it display.


What am i missing





Persist data in a dynamically populated ListBox in a user control


Hi All,

I am trying to persist data in a dynamically populated ListBox in a user control. Here are the details

I have a user control which contains a a listBox and button. On Page_Load of user control I am populating the ListBox control with some values. On Click of button, I am trying to fetch the values which I have selected in ListBox. Though this seems very simple and straight forward I am unable to fetch values.

My Page_Load Function

void Page_Load(object sender, EventArgs e)










My Click Function

Protected Void Button1_Click(object sender, EventArgs e)


       string strValue = listBox.SelectedValue



I have placed brake point at Page_Load and on click function, I am seeing that the moment the breakpoin

custom control



i want to create  my own button using server control .cs file ..

it should have background color black and foreground color as lime and also it should have

the eventhandler mechanism when we double click on that..

can u provide a code for that...?

custom control


hi.. i want to create a custom control button and textbox using server control.. if i type the text into the textbox,when i click the button it should go to the next page related to that text...

please can u provide a code for this kind of question 

How do I persist custom complex types in design-time


Let's say that I've got one custom webcontrol called MyControl.

public partial class MyControl: WebControl {
public IComplex Complex { get; set; }

The control is a very simple control but it holds an instance of a complex type that is accessable through a property. The property has the propertytype IComplex

public interface IComplex {
string Name { get; set; }
List<IComplex> Children {get;}

Let's say that I am able to pick one of several different types of object that derives from IComplex in design-time and assign it to the controls property "Complex" property.

Naturally I would like to persist this information to the HTML-View in a user-friendly way.

Because we don't know what type the user has picked there is no way to instansiate the type if we don't persist the name of that type. The Type could also contain more properties than the Interface the controls property is refering.

<cc1:MyControl id="MyControl1" runat="server">
<Complex> <!-

Custom Control Design view error



I have created a custom control from scratch and it works fine as in you can build the project that uses it and it works fine at runtime. Problem is when you go to design view the control shows an error in the place of where the control should be rendered.

Error: '<SomeValue>' Could not be set to '<SomeProperty>'

This shows up on all my custom set properties. These properties are created as basic as possible. I can give the properties values in Source view and run the app just fine. I can even add a Onclick event. If I don't set any custom properties the control will render fine in Design view. It's only when I set a value to a custom property.

Property Code Example:

public string Text
                string ret = "";
                object obj = ViewState["Text"];
                if (obj != null)
                    ret = obj.ToString();
                return ret;
                ViewState["Text"] = value;

I've even removed the Category and Description tags with no difference.

I don't know if what I said makes sens, but I hope it

Extend ASP.NET: Simplify Data Binding In ASP.NET 2.0 With Our Custom Control


The wwDataBinder control addresses simple control data binding--binding simple form controls like textboxes, checkboxes, and the selected values of list controls to individual data or object values.

Rick Strahl

MSDN Magazine December 2006

Cutting Edge: Custom Data Control Fields


In ASP. NET 2. 0, the GridView and DetailsView controls are designed to work together. They don't merely provide complementary services, they also share a number of helper classes and components. The output of the GridView control consists of a sequence of rows, each with a fixed number of columns.

Dino Esposito

MSDN Magazine January 2006

Dynamically load user control without postback


Hi all,

I need urgent help. (c#coding)

In my base page, I have a dropdownlist control which loads different usercontrols on selectedindexchanged event.

While loading these usercontrols, my page postbacks all the page. I used updatepanel but again same problem.

Is there any way to load controls without postback? I Really need help as soon as possible.

Here is my code:

protected void Page_Init(object sender, EventArgs e)
        if (Session["control"] != null)
            string c = Session["control"].ToString();
            if (c == "1")
                iuc = (IlkogretimUC)LoadControl("~/Controls/Ilkogretim.ascx");
                dl.SelectedValue = Session["control"].ToString();
            else if (c == "2")
                luc = (LiseUC)LoadControl("~/Controls/LiseUC.ascx");
                dl.SelectedValue = Session["control"].ToString();
            else if (c == "3")
                youc = (YuksekokulUC)LoadControl("~/Controls/Yuksekokul.ascx");
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