正在从另一个窗体中清除ListBox



我一直被困在这个问题上,不知道我做错了什么。我正试图通过一个按钮从另一个Form中清除ListBox

在我的主Form上,我有ListBox,我有这个功能:

public void test()
{
this.DeviceList.Items.Clear();
}

在另一个Form上,我有我的按钮:

Form1 mainform = new Form1();
mainform.test();

但当我按下按钮时,什么也没发生。现在,如果我把this.DeviceList.Items.Clear();换成MessageBox.Show("test");,效果很好。但如果我使用this.DeviceList.Items.Clear();,则不会。

我尝试在没有this的情况下使用,但仍然存在相同的问题。

在当前代码中:

Form1 mainform = new Form1();
mainform.test();

创建表单不要Show,而是清除其DeviceList。您应该找到现有表格,例如:

using System.Linq;
...
var mainform  = Application
.OpenForms
.OfType<Form1>()     //TODO: put the right type if required
.LastOrDefault();    // if you have several intances, let's take the last one
if (mainform  != null) // if MainForm instance has been found...
mainform .test();    // ... we clear its DeviceList

最新更新