R – Asp.Net 2 Custom Server Controls Properties

asp.netcompositecustom-server-controls

I am having a very hard time finding a standard pattern / best practice that deals with rendering child controls inside a composite based on a property value.

Here is a basic scenario. I have a Composite Control that has two child controls, a textbox and a dropdown. Lets say there is a property that toggles which child to render.

so:

myComposite.ShowDropdown = true;

If true, it shows a dropdown, otherwise it shows the textbox.

The property value should be saved across postbacks, and the the correct control should be displayed based on the postback value.

Any good examples out there?

Best Answer

You use ViewState to store property value so that it persists between postbacks but you have to do it correctly.

public virtual bool ShowDropdown
{
   get
   {
      object o = ViewState["ShowDropdown"];
      if (o != null)
         return (bool)o;
      return false; // Default value
   }
   set
   {
      bool oldValue = ShowDropdown;
      if (value != oldValue)
      {
         ViewState["ShowDropdown"] = value;
      }
   }
}

Probably somewhere in your Render method you show or hide DropDown control based on the property value:

dropDown.Visible = ShowDropDown;
textBox.Visible = !ShowDropDown;

See also Composite Web Control Example.