UserControl how to remove it

3

I'm working on a desktop application windows form , when I close a UserControl I do it in the following way.

private void _proveedor_ProveedorClose(object sender, EventArgs e)
    {
        pnlPiso.Controls.Remove(_proveedor);
        dgvHelper.DataSource = null;
    }

The UserControl that I use call them to a panel that serves as floor as the pnlPiso . But the funny thing is that in UserControl I have a DGV loaded with 10 records. Then I go to the db and manually delete 5 records, I close the UserControl with the code that I show up lines and when I call again the UserControl shows me in the DGV 10 records but if it should only show 5 records.

Note: the dgvHelper is from another DGV that has nothing to do with the DGV that I am mentioning. How should I destroy or erase from memory the UserControl so that when I call it again, it shows me the real data?

I can only see the real data when I leave the visual studio and flight to open the app.

    
asked by Pedro Ávila 03.05.2016 в 00:19
source

2 answers

0

The problem I had was that I was initializing the variables of calling my UserControl in the constructor of the MDI form that is why they were destroyed. Change the code of the constructor to the click event where it called the UserControl.

private void btnMenuProducto_Click(object sender, EventArgs e)
    {
        dgvHelper.DataSource = null;
        var producto = CompositionRoot.Resolve<ucProducto>();
        this.CurrentControl = producto;
    }

With this I managed to solve the problem I had.

    
answered by 03.05.2016 / 20:13
source
2

Basically, you can use a foreach cycle to go through the controls that are inside the Panel ( pnlPiso ), then call the < strong> Clear () of the panel and thus the instances created within the panel are removed.

Your code would look like this:

private void _proveedor_ProveedorClose(object sender, EventArgs e)
{
    dgvHelper.DataSource = null;
    foreach (Control control in pnlPiso.Controls)
    {
        control.Dispose();
    }
    pnlPiso.Controls.Clear();        
}  

The cycle is not really necessary, but in this way we ensure that the GC ( Garbage Collector ) does its work practically instantaneously.

    
answered by 03.05.2016 в 15:44