从另一个窗体中清除列表框
Clearing ListBox from another Form
我一直卡在这上面,不知道我做错了什么。我正在尝试通过按钮从另一个 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
。你应该找到一个 existing 表格,例如:
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
我一直卡在这上面,不知道我做错了什么。我正在尝试通过按钮从另一个 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
。你应该找到一个 existing 表格,例如:
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