5

Access a member variable from a static method?

 2 years ago
source link: https://www.codesd.com/item/access-a-member-variable-from-a-static-method.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Access a member variable from a static method?

advertisements

I am writing a WinForms application in C# .NET and want to update the listview from the worker thread. I have read just about every post here on this but don't really fully understand the use of Invoke and delegates. In fact a few examples on here won't even compile as it complains of calling a non-static control from a static function.

I have a ListViewItem which I just want to pass to the UI thread via AddListItem(...). What is the best way to do this?

At present I have

this.lvcontrol.Invoke(new Action(() => lvcontrol.Items.Add(item)));

This is from MyForm::AddListView() which is a static function. But of course the compiler complains that you can't call "this" or just "lvcontrol" from a static method. If the method isn't static I can't call the method from the static worker thread which is a member function of the Form.


You need a reference to the lvcontrol in order for the code to know which one you are trying to update (you could have two copies of the form open!).

If lvcontrol is a variable then drop the this at the begining eg

lvcontrol.Invoke(new Action(() => lvcontrol.Items.Add(item))

If it isn't your code is going to either all have to be non-static or you will need to pass a reference to the form around (and use that reference instead of the this, eg if frm is a reference to the form

frm.lvcontrol.Invoke(new Action(() => frm.lvcontrol.Items.Add(item))


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK