1
\$\begingroup\$

I wrote a custom server control. The data in it can be manipulated on the client and the changes will be written into the hidden field. The data represents a property of the control and should be retrieved on a postback. I achieved this by using the value changed event to set the property and all its dependencies. Is this a good a way to do this? Or can this code be improved?

public class Control : CompositeControl {

  private bool mProperty;
  private HiddenField hiddenField;


  public virtual bool Property {
    get {
      return mProperty;
    }
    set {
      mProperty = value;
      if (contentPanel != null) contentPanel.Visible = value;
      if (hiddenField != null && hiddenField.Value != value.ToString().ToLower()) hiddenField.Value = value.ToString().ToLower();
    }
  }
  protected override void CreateChildControls() {
    Controls.Clear();
    CreateControlHierarchy();
    ClearChildViewState();
  }
  protected virtual void CreateControlHierarchy() {
    CreateHiddenField();
    CreateContent();
  }

  protected virtual void CreateHiddenField() {
    hiddenField = new HiddenField();
    hiddenField.ID = "hiddenField";
    hiddenField.Value = Property.ToString().ToLower();
    hiddenField.ValueChanged += hiddenField_ValueChanged;
    Controls.Add(hiddenField);
  }  
  protected virtual void CreateContent() {
    contentPanel = new Panel();
    contentPanel.ID = "content";
    contentPanel.Vsiible = Property;
    Controls.Add(contentPanel);
  }
  void hiddenField_ValueChanged(object sender, EventArgs e) {
    Property = Convert.ToBoolean(hiddenField.Value);
  }
  protected override void OnInit(EventArgs e) {
    EnsureChildControls();
    base.OnInit(e);
  }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can just expose hiddenField.Value in the property.

public bool Property
{
    get
    {
        EnsureChildControls();
        return Convert.ToBoolean(hiddenField.Value);
    }
    set
    {
        EnsureChildControls();
        hiddenField.Value = value.ToString();
    }
}

Property will expose the current value on postback by it self.

You could also expose an event on your control that you refire in the ValueChanged event of the hidden field.

public event EventHandler PropertyChanged;

...

void hiddenField_ValueChanged(object sender, EventArgs e)
{
    ContentPanel.Visible = Property;
    if (PropertyChanged != null) PropertyChanged(this, EventArgs.Empty);
}

I moved the visibility here since it's more related to the value changing than the property itself.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.