Problem with datagrid - ObjectDisposedException when second time dispose

A

Adam

Hello,
I am still learning C#, so please bear with me.
I have a two Form, from first I open second form with datagrid. When I
Dispose datagrid second time I get a ObjectDisposedException.

In first (main) form I have a button with code under onclick event:

temp_n = this.Text;
this.Text = string.Empty;
Form1 frm1 = new Form1;
frm1.ShowDialog();
frm1.Dispose();
this.Text = temp_n;


and in second form:

private void Form1_Load(object sender, EventArgs e)
{
ceCmd = Global.DatabaseConnection.CreateCommand();
ceCmd.CommandText = "select col1,col2 from table";
ceCmd.CommandType = CommandType.Text;
ceResSet = ceCmd.ExecuteResultSet(ResultSetOptions.Scrollable);
dataGrid1.DataSource = ceResSet;
}

and

private void Form1_Closed(object sender, EventArgs e)
{
if (ceResSet != null)
{
ceResSet.Close();
ceResSet.Dispose();
}
if (dataGrid1 != null) dataGrid1.Dispose();
}

and when I twice opened and closed second Form i get a
ObjectDisposedException on
"if (dataGrid1 != null) dataGrid1.Dispose();"
it's strange to me because when i put button on second form and add event:

private void Button_Click(object sender, EventArgs e)
{
if (ceResSet != null)
{
ceResSet.Close();
ceResSet.Dispose();
}
if (dataGrid1 != null) dataGrid1.Dispose();

this.Close();

}

everything is OK. So i tried put datagrid1.Dispose() on override OnClosing
and override OnClosed but with no change - DisposedException still occurs.

So, what I'm doing wrong?
 
A

Adam

Dnia Wed, 14 Nov 2007 23:58:48 +0100, Adam napisa³(a):
Hello, [cut]
So, what I'm doing wrong?

Problem exist when datagrid have some data, if is empty everything is ok
but when have data i cannot dispose it in Form_on_closing event. Why?
 
G

Guest

Why are you trying to dispose the grid control in your closing event? Remove
this and let the overloaded dispose method do it, as it will. You are calling
Dispose after your class has exited which is finalizing all controls. So
effectively, the Dispose method is trying to release the grid even though it
has already been released in your closing event.

It is good practice to call Dispose on your form, but only Dispose of
resources in the Dispose method - no where else.

As you are using C# trying using the following syntax:

using (Form1 frm1 = new Form1())
{
frm1.ShowDialog();
}

As long as the IDiposable interface is implemented (which is in this case by
class Control), then the Dispose method will be called on frm1 without you
having to explicitly call it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top