Nick
Nick

Reputation: 19684

User Control on Panel remains visible when visible set to false

I am trying to swap out user controls dynamically. How can I 'hide' controls on a panel? Removing them from the Controls collection does not work and setting the control's visible property does not work.

ServersView servers = new ServersView();           
       ServersPresenter presenter = new ServersPresenter(servers);
       _view.SettingsPanel.Controls.Add(servers);
       _view.SettingsPanel.Controls[0].Visible = false;

The new control is not visible after added because the other user control is still visible. Can someone tell me how to hide the user controls?

Thanks

Upvotes: 1

Views: 878

Answers (2)

Dmitry Karpezo
Dmitry Karpezo

Reputation: 1058

Are you sure the control collection is empty at the moment you add a new item? When you add an item, it is placed at the end of the collection, so it's better to refer the last item.

Try to get index of the control in the collection:

int index = _view.SettingsPanel.Controls.GetChildIndex(servers);
_view.SettingsPanel.Controls[index].Visible = false;

IMHO.

Upvotes: 1

xpda
xpda

Reputation: 15813

Check to make sure that controls[0] is the really the control you think it is. For example, is servers the same object as _view.SettingsPanel.Controls[0]? Would it be better to add all the controls once, maybe at form load or some early time, then set the visible property later? That way, you don't have to worry about adding too many controls later on.

Upvotes: 1

Related Questions