Hi,
Using VS2005, writing in VB.
I'm trying to have a form dispose of itself because of a load error where it fails to find its settings files.
Problem is, if I call Me.Close(), there's an unhandled ObjectDisposedException referring to the form itself.
I'm guessing that this is because of something along the lines of "I'm calling the load code during the constructor, but the error is occurring during the load code and so my constructor is then returning a dead object." but I could easily be wrong.
Can anyone recommend me a way to work around this problem so that I can properly have this check
Thanks,
KF

Trying to close a form following a loading error
baskark
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
throw new MyFormLoadException("no can do");
}
}
public class MyFormLoadException : Exception {
public MyFormLoadException(string msg) : base(msg) { }
}
In Program.cs:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try {
Application.Run(new Form1());
}
catch (MyFormLoadException ex) {
MessageBox.Show(ex.Message, "Startup failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
TanLU
Hi KFrost
The easiest way around this issue is to move your startup code to the form's load event instead of running it in the constructor. If you close in the load event you'll be OK. Of course you could set a boolean flag if the constructor failed, catch it in the load event, and close from there but all the code purists out there would be horrified ;-)
Seriously in general practice you want to keep constructors short and sweet. The load event will be triggerred at the conclusion of the constructor, after the .net forms plumbing does it's magic, but before the form is receiving input from the user. Once the form renders on the screen the activate event triggers unless it's an MDI child in which case the parent's activate fires.
HTH
Javfarary
Ah, Form.Load...
Never actually used that under .net before. I always kind of assumed that it had been replaced by constructors.
Moved the code in question, though, and it all works fine now.
Cheers.
::sheepishly goes to look up how Form.Load works these days::