c# - How to correctly solve this situation regarding DataContext, IDisposable and Controls.Clear() -
i'm using entity framework 4 orm on windows forms application.
i have series of usercontrols function if forms or areas inside mainform.cs. reason did interchange display in 'content' block of form.

so when click on buttons (on left), .clear() whatever controls in 'content' block , add select form.
here's relevant code:
private void navigationbar_click(object sender, eventargs e) { //panelholder regular winforms panel control. panelholder.controls.clear(); switch (sender.tostring()) { case "alumnos": var studentform = new students.studentlisterform(); panelholder.controls.add(studentform); break; case "personal": var personalform = new personal.personallisterform(); panelholder.controls.add(personalform); break; case "atendencia": var atendenciaform = new attendance.studentattendanceform(); atendenciaform.showdialog(); break; case "cursos": var gradeform = new grades.gradelisterform(); panelholder.controls.add(gradeform); break; case "centralizador": messagebox.show("est"); break; case "libretas": scores.studentscores scores = new scores.studentscores(); panelholder.controls.add(scores); break; } } now, each usercontrol manages it's own creation , usage of data context. inside of each of these controls have code example:
using (graderepository repo = new graderepository()) { cmbgrade.datasource = repo.findallgrades(); } and here's code graderepository:
public class graderepository : idisposable { colegiodbv2entities db = new colegiodbv2entities(); public iqueryable<grade> findallgrades() { return db.grades; } public void add(grade grade) { db.addtogrades(grade); } public void savechanges() { db.savechanges(); } public void dispose() { db.dispose(); } } this ensure use context, data, close , dispose of it.
my problem lies when click on 1 of buttons told top, panelholder.controls.clear(); line fires objectdisposedexception.
i've temporarily solved removing using statements in relevant areas, looks like:
graderepository repo = new graderepository(); cmbgrade.datasource = repo.findallgrades(); can suggest correct way tackle problem? .clear() method dispose of objects, using using statement not needed?
thank time.
make datacontext property on scope of form , let destroy when form destroyed.
Comments
Post a Comment