如何重新打开以前关闭的窗口窗体.“无法访问已释放的对象”

本文关键字:访问 对象 释放 窗体 窗口 何重新 | 更新日期: 2023-09-27 18:36:32

我在这里读过一些类似的东西,但没有找到我的问题的解决方案。

我正在将数据从form1发送到我的tempGraph表单。一切都很好,直到我关闭我的 tempGraph 窗体并尝试重新打开它。当我尝试重新打开时,它说CANNOT ACCESS A DISPOSED OBJECT现在是我的问题。

如何才能再次打开我的临时图表?

这是我将数据发送到不同形式(如我的 tempGraph)的代码:

 public void SetText(string text)//Set values to my textboxes
{
    if (this.receive_tb.InvokeRequired)
    {   
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {  var controls = new TextBox[]
       {    wdirection_tb,
            wspeed_tb,
            humidity_tb,
            temperature_tb,
            rainin_tb,
            drainin_tb,
            pressure_tb,
            light_tb
        };
        data = text.Split(':');
        for (int index = 0; index < controls.Length && index < data.Length; index++) // This code segment Copy the data to TextBoxes
        {   
            TextBox control = controls[index];
            control.Text = data[index];
            //planning to pud the code for placing data to DataGridView here.
        }
            //or Place a code here to Call a UDF function that will start copying files to DataGridView
        //index1++; //it will count what row will be currently added by datas
        if (data.Length != 0)
        { datagridreport(temperature_tb.Text.ToString(), humidity_tb.Text.ToString(),     pressure_tb.Text.ToString());  }  

        //sending of data to each graph. THIS CODE SENDS DATA TO OTHER FORMS
        tempG.temp.Text = temperature_tb.Text;
        humdidG.humid.Text = humidity_tb.Text;
        pressG.Text = pressure_tb.Text;

        //updating textbox message buffer
        this.receive_tb.Text += text;
        this.receive_tb.Text += Environment.NewLine;
    }
}                

以下是我打开位于我form1中的临时图的代码:

private void temperatureToolStripMenuItem_Click(object sender, EventArgs e) 
{            
    tempG.Show();
}

我使用右上角的 X 按钮关闭我的 tempG/tempGraph 或使用带有以下命令的按钮关闭它:

private void button1_Click(object sender, EventArgs e)
{
    timer1.Stop();
    timer1.Enabled = false;
    TempGraph.ActiveForm.Close();
}        

注意:当我在关闭 tempGraph 后重新打开它时,会发生错误。

如何重新打开以前关闭的窗口窗体.“无法访问已释放的对象”

发生这种情况是因为您已将对当前tempGraph表单的引用存储在全局变量中,并且当您关闭当前实例时,该变量仍然包含对现在释放的对象的引用。

解决方案是在主窗体中获取关闭事件并重置为空全局变量。

因此,假设要更改菜单单击以

private void temperatureToolStripMenuItem_Click(object sender, EventArgs e) 
{            
    if(tempG == null)
    {
        tempG = new tempGraph();
        tempG.FormClosed += MyGraphFormClosed;
    }
    tempG.Show();                
}

并在主窗体中添加以下事件处理程序

private void MyGraphFormClosed(object sender, FormClosedEventArgs e)
{
    tempG = null;
}

现在,当 tempG 引用的tempGraph表单实例关闭时,您将收到通知,您可以将全局变量tempG设置为 null。当然,现在你需要在使用该变量之前检查所有地方,但是当你调用tempG.Show()时,你肯定会让它指向一个正确的非DISPLACEE实例。