I am programming a inventory system in Windows Forms using C# and I designed it with a admin dashboard looking. I am using MDI and I load the products by clicking the products button.
When loading the child form everything works ok:
But when I load the products again and again I noticed that in Windows Task Manager the program is consuming too much memory every time I load the products or click products button. The memory consumption is being very aggressive.
This is my code:
loading the child form from parent:
public partial class Layout2 : BaseContext
{
public Layout2()
{
InitializeComponent();
}
//loads the products form
private void ventas_boton_Click(object sender, EventArgs e)
{
var frm = new Inventario();
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
panel3.Controls.Add(frm);
frm.WindowState = FormWindowState.Maximized;
frm.Visible = true;
}
}
child form stuff
public partial class Inventario : BaseContext
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CargarLista();
}
public virtual void CargarLista()
{
var productos = _inventarioRepository.GetList();
ListaProductos.DataSource = productos;
}
}
Base Context
public class BaseContext: Form
{
// contexto base, todos los forms deben heredar esta clase por orden.
private bool _disposed = false;
protected Context _context { get; set; }
public BaseContext()
{
_context = new Context();
}
protected override void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) _context.Dispose();
_disposed = true;
base.Dispose(disposing);
}
}
I think var frm = new Inventario();
is causing the problem because it is creating new object every time I click the button to show the form.
My issue is simple but I am new at Windows Forms, How do I solve this memory consumption every time I open or update the products form?