-1

ここでこのようなことをいくつか読みましたが、問題の解決策が見つかりませんでした。

form1 から tempGraph フォームにデータを送信しています。tempGraph フォームを閉じて再度開くまで、すべて問題ありません。再開しようとすると、CANNOT ACCESS A DISPOSED OBJECTどちらが今私の問題であるかが表示されます。

tempGraph を再び開くにはどうすればよいですか?

これは、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;
    }
}                

my にある tempGraph を開く際のコードは次のとおりです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 を閉じた後に再度開くと、エラーが発生します。

4

1 に答える 1

3

これは、現在のフォームへの参照をグローバル変数に格納しておりtempGraph、現在のインスタンスを閉じたときに、その変数がまだ破棄されたオブジェクトへの参照を保持しているために発生します。

解決策は、メイン フォームでクローズ イベントを取得し、グローバル変数を null にリセットすることです。

メニューのクリックを次のように変更するとします。

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;
}

これで、tempGraph参照されているフォーム インスタンスが閉じられると通知され、グローバル変数を null にtempG設定できます。tempGもちろん、その変数を使用する前にどこでもチェックする必要がありますが、 tempG.Show() を呼び出すと、正しく NON DISPOSED インスタンスを指すようになります。

于 2015-01-06T18:36:08.420 に答える