B Z
B Z

Reputation: 9453

Asp.Net 2 Custom Server Controls Properties

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?

Upvotes: 1

Views: 703

Answers (2)

Pavel Chuchuva
Pavel Chuchuva

Reputation: 22465

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.

Upvotes: 3

ckramer
ckramer

Reputation: 9443

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

Upvotes: 0

Related Questions