C. Cristi
C. Cristi

Reputation: 579

Using list from classes in forms

Say I have the following class:

public class ListArticle
    {
        public List<string> Clothes
        {
            get
            {
                return _clothes;
            }
            set
            {
                if (value != _clothes) _clothes = value;
            }
        }

        public List<string> Colors
        {
            get
            {
                return _colors;
            }
            set
            {
                if (value != _colors) _colors = value;
            }
        }

        private List<string> _clothes { get; set; }
        private List<string> _colors { get; set; }
    }

I want to add strings to my lists into, let's say, form1 and use them in another form such as form2. How is this possible?

Upvotes: 0

Views: 101

Answers (2)

404
404

Reputation: 8582

Addressing the issue in your comment

I tried to declare a variable like this in form1: ListArticle Names = new ListArticle(); but when I try to use properties like Names.Clothes.Add(); it doesn't work..

Depends what you mean by "it doesn't work", but if that's really all you did it sounds like you haven't actually created your Lists yet.

So change class to this and try again:

public class ListArticle
{
    public List<string> Clothes { get; private set; }
    public List<string> Colors { get; private set; }

    public ListArticle()
    {
        Clothes = new List<string>();
        Colors = new List<string>();
    }
}

(edit)

Doing the above will allow you to do something like Names.Clothes.Add() without an exception being thrown (which was how I interpreted your comment).

Now let's see how you can get the same data from Form1 into Form2:

Form1.cs

public class Form1 : Form
{
    private readonly ListArticle _articles = new ListArticle();

    // assume strings have been added to articles by this point.

    // option 1 - use same ListArticle instance
    public void Foo()
    {
        var form = new Form2();
        form.Articles = _articles; 
    }

    // option 2 - add strings to new ListArticle
    public void Bar()
    {
        var articles = new ListArticle();
        articles.Clothes.AddRange(_articles.Clothes);
        var form = new Form2();
        form.Articles = articles;
    }
}

public class Form2 : Form
{
    public ListArticle Articles { get; set; }
}

I must stress of course that these are not the only ways and certainly not the best ways to do it - just a couple simple examples to hopefully accomplish what you want. If this still doesn't work then you will have to be much clearer about what end result you expect, and how exactly you're trying to accomplish it.

Upvotes: 1

NicoRiff
NicoRiff

Reputation: 4883

You can make the constructor of Form2 accept a ListArticle object. Also if you will only have one ListArticle across your system then you can make the class and all of its properties as Static.

Upvotes: 0

Related Questions