Hello im pretty new to c# just downloaded VS2012 and created my new Application, but im getting a really strange Exception, I guess its my fault but again im really new to this
the exception occours when closing form2 that form1 created. this only occurs when an object its placed on form2.
I just got 2 forms with a button on each, button on form1 calls form2, when form2 is closed I show again form1, after a few seconds it throws InvalidOperationException on line base.Dispose
here is the code that trhows the exception
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing); // here is the exceptjion
}
Here is form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2(this);
frm.Show(this);
this.Hide();
}
}
Here is form2
public partial class Form2 : Form
{
private Form frm;
public Form2(Form frm) : this()
{
this.frm = frm;
}
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
frm.Show();
this.Close();
}
}
Here is the stacktrace
No se controló System.InvalidOperationException
HResult=-2146233079
Message=Operación no válida a través de subprocesos: Se tuvo acceso al control 'button1' desde un subproceso distinto a aquel en que lo creó.
Source=System.Windows.Forms
StackTrace:
en System.Windows.Forms.Control.get_Handle()
en System.Windows.Forms.Control.get_InternalHandle()
en System.Windows.Forms.Control.DestroyHandle()
en System.Windows.Forms.Control.Dispose(Boolean disposing)
en System.Windows.Forms.ButtonBase.Dispose(Boolean disposing)
en System.ComponentModel.Component.Dispose()
en System.Windows.Forms.Control.Dispose(Boolean disposing)
en System.Windows.Forms.Form.Dispose(Boolean disposing)
en PruebaExceocion.Form2.Dispose(Boolean disposing) en c:\Users\Alex\Documents\Visual Studio 2012\Projects\PruebaExceocion\PruebaExceocion\Form2.Designer.cs:línea 20
en System.ComponentModel.Component.Dispose()
en System.Windows.Forms.Form.WmClose(Message& m)
en System.Windows.Forms.Form.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
InnerException:
If you just simply program with 2 forms, then calling one from the other’s button can be done also simply like
And no more, you can close the second form whenever you want without any error (I tested this on vs12). It will create a new instance of the Form2 with each button click.
So it becomes a bit trickier if you only want one and the same instance of form2 displayed with each click.