簡體   English   中英

將列表從Form3傳遞到Form1

[英]Pass List from Form3 to Form1

我有3種形式:form1(我想使用來自form3的List,在其中創建List並向其中添加內容),form2(其中包含一個返回form1的按鈕和一個進入form3並獲取值的按鈕名單。

我嘗試創建以下類:

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>();
        }
    }

然后聲明嘗試像這樣從form3向列表中添加內容:

//這是宣言

public ListArticle _articles = new ListArticle();

    public ListArticle Articles
    {
        get
        {
            return _articles;
        }
        set
        {
            _articles = value;
        }
    }

這是我添加的方式:

_articles.Clothes.Add("T-shirt " + tshirt_number.ToString());
_articles.Colors.Add(closestColor2(clist, color));

這就是我試圖獲取值的方式:

當我關閉form3時

我這樣做:

Form2 frm = new Form2();
frm.Show();
Articles = _articles;
this.Hide();

在form2中,我什么也沒做。

在form1中,我試圖這樣做:

//宣言

public ListArticle Articles;

public ListArticle _articles
{
   get
   {
     return Articles;
   }
   set
   {
     Articles = value;
   }
}

//這是我嘗試執行的操作,但是每次都會返回null。

private void button3_Click(object sender, EventArgs e)
    {
        try
        {
            Form3 f = new Form3();

            f.Articles = Articles;

            foreach (string c in Articles.Clothes)
            {
                MessageBox.Show(c);
            }
        }
        catch 
        {
            MessageBox.Show("Articles is null.");
        }

    }

如果您希望能夠在所有形式之間共享文章,則可以將“衣服和顏色”集合設為靜態:

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

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

然后,您可以像這樣的一種形式添加文章:

ListArticle.Clothes.Add("T-shirt " + tshirt_number.ToString());
ListArticle.Colors.Add(closestColor2(clist, color));

...並從另一種形式檢索文章:

private void button3_Click(object sender, EventArgs e)
{
    try
    {
        foreach (string c in ListArticle.Clothes)
        {
            MessageBox.Show(c);
        }
    }
    catch
    {
        MessageBox.Show("Articles is null.");
    }
}

使用這種方法,您不必在任何一種形式中都創建任何其他“文章”屬性。 您只需從所有表單訪問相同的靜態集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM