Search code examples
c#winformsuser-controls

How do I clear a user control from a winform?


This is probably a basic question, but I can't find answers because the terms are generic.

I am building a WinForm aplication. Its purpose is to set up memory in a certain chip. I think the best way to organize the application is to have a user control for each chip type, derived from a generic parent class. Think of the children as "iphone," "android" and "blackberry," derived from a parent class "phone".

VS2017 Designer has a Panel where I want the control to be. On startup, I generate an object of the base class and add it to the panel. When I press a button, the old object is deleted and replaced with a new one. Each class has just one control, a label with distinctive text.

The problem is, after I press the button, I see both texts. The panel's Controls collection has just one element, but I see the text from both objects. I have tried Refresh, Update and Invalidate withe the same results.

What do I have to do to make the old text "go away" so the only thing I see is the latest object?

    private ChipMemBase ChipMemControl = new ChipMemBase();
    public Form1()
    {
        InitializeComponent();
        //tbFeedback.Text = string.Format(fmtString, 0, 1, 2, 3, 4, 5);
        cbChipName.SelectedIndex = 0;
        tbVersion.Text = Version;
        OriginalWindowColor = tbFeedback.BackColor;
        ShowChipMemControl();
        PrintToFeedback(Version);
    }
    private void ShowChipMemControl()
    {
        var ctl = pnlChipMem.GetChildAtPoint(new Point(5,5));
        if (null != ctl)
        {
            if (ctl != ChipMemControl)
            {
                pnlChipMem.Controls.Remove(ctl);
                ctl.Dispose();
                pnlChipMem.Update();
                Refresh();
            }
        }
        if (null != ChipMemControl)
        {
            pnlChipMem.Controls.Add(ChipMemControl);
        }
    }
    private void btnMakeChipMemory_Click(object sender, EventArgs e)
    {
        ChipMemControl = new ChipMemGen2();
        ShowChipMemControl();
    }

Screenshots before and after clicking Create


Solution

  • Got it. The problem was from inheritance, not window behavior. Control lblDefault in the base class, carrying the inconvenient text, was still present in the child class. I had to make it Public in the base class and remove it in the child class constructor:

            InitializeComponent();
            Controls.Remove(lblDefault);
            lblDefault.Dispose();
            lblDefault = null;
    

    The clue was this article and project: dynamically-and-remove-a-user-control