c#从另一种形式清除列表框

问题描述 投票:0回答:1

我一直坚持下去,不知道我在做什么错?我正在尝试通过按钮从其他表单中清除列表框。

在我具有列表框的主窗体上,我具有此功能:

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

还有另一种有按钮的表格,我有:

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

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

我尝试使用没有“ this”但仍然是相同的问题。

谢谢!

c# .net winforms function listbox
1个回答
0
投票

在您当前的代码中:

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

您创建表单不要 Show,但清除其DeviceList。您应该找出一个existing表格,例如::

using System.Linq;

...

var form = Application
  .OpenForms
  .OfType<MainForm>()  //TODO: put the right type if required
  .LastOrDefault();    // if you have several intances, let's take the last one

if (form != null)      // if MainForm instance has been found...
  form.test();         // ... we clear its DeviceList
© www.soinside.com 2019 - 2024. All rights reserved.