I have a form and multiple controls.
Say I have a single form and it should contain some controls.
I’m trying to work with a single form and add and remove controls depending on some use cases.
For example, this is a sample code in my form class:
private void AddToControlPanel(UserControl control)
{
this.panelControl.Controls.Add(control);
this.panelControl.Tag = control;
this.panelControl.Size = control.Size;
this.panelControl.Dock = DockStyle.Fill;
control.Show();
}
Above sample adds a control to some panel and shows it.
Problem is I can’t manage to add some other control and drop current one. For example, if some login control authenticates successfully, drop login control itself and show other like a search box control.
How can achieve that?
This is what I’ve tried so far:
if (LoginOK)
{
//Add the next Control I want to load
this.ParentForm.Controls.Add(new CtlPedirDevolucion());
//Remove this actual control
this.ParentForm.Controls.Remove(this);
}
… so later show latest added control using an event handler:
private void FirstForm_ControlRemoved(object sender, ControlEventArgs e)
{
this.Controls[this.Controls.Count - 1].Show();
}
But this isn’t working for me. In addition I don’t like my approach.
Will you suggest me a better way of achieving this please?
I have tried something similar and it works.
Code in your Form:
Code in your Control:
EDIT: My bad, there is no point creating a CtlPedirDevolucion in control that will be removed. It should be instantiated in your Form and there should also be a reference to it. Therefore SwitchControls should have a more complex logic, and maybe more parameters but this is something you can work with. Maybe you could make a switch-case or something that will create a control within your form. I remind you that this is just an example that works but is very bad.