Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Controls from static method?

Hello Why I haven't access to my private control on form (e.g. ListBox) from a static method? How to update control in this case?

EDIT 1.

my code:

ThreadStart thrSt = new ThreadStart(GetConnected);
        Thread thr = new Thread(thrSt);
        thr.Start();

and

static void GetConnected()
    {
        //update my ListBox
    }

So it must be void, without param and be static, right?

EDIT 2.

If someone need solution in WPF then should try this:

private void GetConnected()
    {
        myListBox.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(() =>
                    {
                        myListBox.Items.Add("something");
                    }
                               )
                 );
    }
like image 858
Saint Avatar asked Oct 31 '10 20:10

Saint


1 Answers

Static methods cannot access instance state (such as a non-static control). Either remove static from the method declaration, or pass a reference to the control as argument to the method:

private static void SomeMethod(ListBox listBox)
{
    listBox.Items.Add("Some element");
}

...and call it like so:

SomeMethod(MyListBox);

Update
There are different ways to do asynchronous things in the UI (now assuming winforms). I would recommend you to look into using BackgroundWorker (search here on SO; plenty of examples). If you really want to do it by creating threads on your own, here is one way to do that:

private void SomeMethod()
{
    string newElement = FetchNextElementToAdd():
    SafeUpdate(() => yourListBox.Items.Add(newElement));
}

private void SafeUpdate(Action action)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke(action);
    }
    else
    {
        action();
    }
}

...and to call it:

Thread thread = new Thread(SomeMethod);
thread.Start();

You can also use the thread pool (preferred over creating your own threads, given that you don't expect them to run for very long):

ThreadPool.QueueUserWorkItem(state => SomeMethod());
like image 77
Fredrik Mörk Avatar answered Sep 20 '22 17:09

Fredrik Mörk