Michael L
Michael L

Reputation: 303

Clearing ListBox from another Form

I have been stuck on this and don't know what I am doing wrong here. I am trying to clear a ListBox from another Form via a button.

On my main Form where I have the ListBox I have this function:

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

And on the other Form where I have my button I have:

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

But when I press the button nothing happens. Now if I switch out this.DeviceList.Items.Clear(); to MessageBox.Show("test"); that works just fine. But not if I am using this.DeviceList.Items.Clear();.

I tried using without this but still the same issue.

Upvotes: 0

Views: 136

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

In your current code:

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

you create a new form don't Show it but clear its DeviceList. You should find out an existing form, e.g.:

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

Upvotes: 1

Related Questions