如何关闭并重新打开另一个表单中的表单?

时间:2019-10-08 13:10:52

标签: c# winforms events callback

我有一个包含雇员列表的列表框,当调用selected index changed事件时,将打开一个新表单,其中包含一些雇员信息,例如电子邮件,姓名,位置。但是,当单击另一个用户时,我希望关闭上一个表单并打开新选择的员工。

这是我用来尝试关闭表单然后重新打开它的当前代码,但是我在dispose调用中遇到错误:

System.ObjectDisposedException: 
"Cannot access a disposed object. Object name: 'EmployeeInfoPopup'.

代码位于事件EmployeeListBox_SelectedIndexChanged中。

EmployeeInfoPopup popup = new EmployeeInfoPopup();
if(popup.Enabled == true)
{
     popup.Dispose();
     popup.employeePopupLayout(employeeListBox.SelectedIndex);
     popup.Show();
}
else
{
     popup.employeePopupLayout(employeeListBox.SelectedIndex);
     popup.Show();
}

这是在EmployeeInfoPopup表单中调用的方法

public void employeePopupLayout(int currentEmployeeIndex)
{
     SeatingChart_2_0 seatingChart = new SeatingChart_2_0();
     employeeLabel.Text = ($"Name: {seatingChart.employeesNames[currentEmployeeIndex]}\nEmail: {seatingChart.employeesEmails[currentEmployeeIndex]}\nBuilding: {seatingChart.employeesBID[currentEmployeeIndex]}\nFloor: {seatingChart.employeesFID[currentEmployeeIndex]}\nSeat: {seatingChart.employeesSID[currentEmployeeIndex]}");
}

2 个答案:

答案 0 :(得分:0)

您可以尝试以下模式:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;

static private Dictionary<int, EmployeeInfoPopup> EmployeeInfoForms 
  = new Dictionary<int, EmployeeInfoPopup>();

private void EmployeeListBox_SelectedIndexChanged(object sender, EventArgs e)
{
  int index = EmployeeListBox.SelectedIndex;
  if ( EmployeeInfoForms.ContainsKey(index) )
  {
    EmployeeInfoForms[index].Close();
  }
  else
  {
    EmployeeInfoPopup popup = new EmployeeInfoPopup();
    EmployeeInfoForms.Add(index, popup);
    popup.employeePopupLayout(index);
    popup.Show();
  }
}

static internal void EmployeeInfoPopupClosed(EmployeeInfoPopup sender)
{
  var key = EmployeeInfoForms.FirstOrDefault(v => v.Value == sender).Key;
  if ( key != null )
    EmployeeInfoForms.Remove(key);
}

我们使用打开的EmployeeInfoPopup字典,该字典由列表框项目索引键入。

如果您将Close更改为Show,则可以同时打开多个表单。

然后,我们检查是否已创建该表单以关闭(或显示)该表单,或者创建,初始化和打开该表单。

FormClosed的{​​{1}}事件上,添加:

EmployeeInfoPopup

如果您只有TheFormWithTheListBoxClassName的一个实例,则此方法很好,否则,需要使用由TheFormWithTheListBoxClassName键入的上一词典的字典来管理实例,需要更多代码。

让我知道您的情况,我将更新代码。

答案 1 :(得分:-1)

如果实例为@Injectable({ providedIn: 'root' }) export class UploaderService extends RestService { constructor(http: HttpClient) { super(http); } } d

Dispose

您将无法再打开它({em {em}已释放所有必需的资源,例如 popup.Dispose();

Handle

您可以尝试找出是否打开了 popup.Show(); // <- Will throw exception 表单(以及EmployeeInfoPopup表单):

Close

如果要删除所有这样的表格:

  using System.Linq;

  ... 

  // Close the last opened EmployeeInfoPopup if it exists
  Application
    .OpenForms
    .OfType<EmployeeInfoPopup>()
    .LastOrDefault()
   ?.Close();

然后创建并打开一个新的 var forms = Application .OpenForms .OfType<EmployeeInfoPopup>() .ToArray(); foreach (var form in forms) form.Close(); 距离

EmployeeInfoPopup