Question

Okay, I think I'm just making a stupid mistake here, but I want to create a Control (derived from System.Web.UI.Control) that is collapsible, using the good ol' ASP.net ViewState/PostBack model.

I have an ImageButton in my class, which I initialize in the OnInit() Event:

    private ImageButton _collapseImage;
    protected override void OnInit(EventArgs e)
    {
        if (_collapseImage == null)
        {
            _collapseImage = new ImageButton();
            _collapseImage.Click += CollapseImageClick;
        }
        _collapseImage.ImageUrl = string.Format("/images/{0}", IsCollapsed ? "plus.gif" : "minus.gif");
        _collapseImage.Width = 16;
        _collapseImage.Height = 16;
    }

IsCollapsed is a boolean, and the CollapseImageClick just toggles it:

    private void CollapseImageClick(object sender, ImageClickEventArgs e)
    {
        IsCollapsed = !IsCollapsed;
    }

My CreateChildControls is then checking this parameter:

 protected override void CreateChildControls()
    {
        Panel pnl = new Panel();

        pnl.Controls.Add(_collapseImage);
        if(!IsCollapsed)
        {
            // Add some more Controls
        }
        Controls.Add(pnl);
    }

Unfortunately, it does not work. I click on the ImageButton, the page does it's postback, but then it does not change it's state - if it was expanded before, it's still expanded after.

In the constructor, I set EnableViewState = true;

Any clue what I am missing in order to persist these changes?

Was it helpful?

Solution

Are you actually saving the state of your panel (the collapsed boolean) into the viewstate?

ViewState("collapsed") = Collapsed

The viewstate does not automatically save any property/variable you have, you have to tell it what to do.

OTHER TIPS

If ViewState does not work for you, you could always try to store it as a session.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top