views:

412

answers:

2

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?

A: 

I would think something like:

public bool ShowDropDown
{
    get{ return (bool)ViewState["ShowDropDown"]; }
    set{ ViewState["ShowDropDown"]; }
}


private  void Page_Load(object sender, EventArgs e)
{
    DropDaownControl.Visible = ShowDropDown;
    TextBoxControl.Visible = !ShowDropDown;
} 
/* some more code */
ckramer
If this property is not set by the caller you will get NullReferenceException in the get method.
Pavel Chuchuva
+3  A: 

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.

Pavel Chuchuva