1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 */

1 Comment

If this property is not set by the caller you will get NullReferenceException in the get method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.