I’ve a problem with my C# Code. At the moment I try to program a Windows Forms Application with more than one Window.
Now my problem:
At the first window I’ve a combobox with some values. When I click on a button, the second window opens and there it should be possible to add a value to this combobox on the first form.
The problem is that in the first window I´ve a LinkedList where my values are in.
Like this:
public LinkedList<String> sample = new LinkedList<String>();
hase.AddFirst("test");
combobox.Items.AddRange(sample.ToArray());
Now, in the second window the LinkedList isn’t available, even if I make it public.
What is the best way to solve this problem?
Hope you understand my problem…
Harald
Without knowing exactly how to are trying to access the LinkedList, it’s hard to say why it isn’t working for you.
Let’s go over what you have. You have a LinkedList, which is an instance variable on a form. Since this LinkedList is an instance variable, it is associated with the instance of the form.
This example below, will not work because it tries to access it statically:
So, we can see this does not work. We have a few options to get this working. First off, one very bad solution would be to actually make
liststatic. Don’t use this option. It’s opens the door for concurrency problems, possibly leaking strong references, etc. Generally, using statics (like a singleton) I would discourage for passing data around for these reasons. The Singleton Pattern has a time and a place, but I don’t think this is it since it can so easily be avoided.OK, since we got the bad solution out of the way, let’s look at a few possible good ones.
Set the list on
MySecondForm. You have a few options for this. The constructor, a property, or a method. For example:This is one possible solution. The constructor is another possible solution as Billy suggested.
Because
LinkedListis a reference type, any changes you make to it on the instance ofMySecondFormwill be reflected on the linked list ofMyForm.