JoshP wrote:
I am new to C# and windows programming. I am trying do create something
fairly simple (at least I think). I have 1 form (Form1). On Form1 I have a
listbox. I also have a Class (Class1). Class1 loops through the local
filesystem. I want Class1 to add filenames to Form1's listbox. I know I
have to use events and delegates, etc but am unsure and I can't find any good
examples. Please provide some help. Examples are great. Thanks.
Why do you know that you have to use events and delegates?
It's not clear from your post how Class1 works, but in the simplest case
all you have to do is make sure that Class1 has access to the reference
to the listbox or the Form1 containing the listbox, and then use that
reference to call a method that will add the filenames to the listbox.
If you get the reference to the listbox instance itself, this is simply
a matter of calling the appropriate add method with the filename. It's
possible you'd prefer to put a public method on the form that handles
the actual interaction with the listbox, so that the listbox isn't
exposed. In that case, your Class1 would need a reference to the form
instance, and would call that public method to do the actual work with
the filename.
If your Class1 does its work in a different thread, then you do run into
a need to use a delegate, but not an event. The reason being that the
act of actually adding the filename to the list box must be done on the
main UI thread, not the thread in which Class1 does its work. In that
case, you'd need to use the Control.Invoke() method, passing it a
delegate that would actually do the work (as above...this works whether
you are calling a public method on the form, or calling a method on the
listbox instance directly). That delegate can be as simple as an
anonymous method, and in fact that's what I'd recommend.
Pete