2017-01-03 46 views
0

末增加我想從Form3Form4Form5Form6Form7Form8創建窗體2與數據的列表_Buffer。我做了工作,但只有1點的形式,如果我嘗試從Form4例如創建另一個列表中添加其他元素,而我已經從Form3添加...在Form2會告訴我只能從Form4元素,而不從Form3我添加的元素先前。下面是我如何做到這一點:通過列表形式之間,並在它

代碼Form2

ListArticle _Buffer = new ListArticle(); 
    public void SetData(ListArticle article) 
    { 
     _Buffer = article; 

    } 

代碼Form3

public ListArticle _articles = new ListArticle(); 

    public ListArticle Articles 
    { 
     get 
     { 
      return _articles; 
     } 
     set 
     { 
      _articles = value; 
     } 
    } 
foreach (Color color in dominantColours) 
{ 
    MessageBox.Show(closestColor2(clist, color)); 
    tshirt_number++; 
    _articles.Clothes.Add("T-shirt " + tshirt_number.ToString()); 
    _articles.Colors.Add(closestColor2(clist, color)); 
    Console.WriteLine("K: {0} (#{1:x2}{2:x2}{3:x2})", color, color.R, color.G, color.B); 
    string hex = color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); 
} 

注:closestColor2返回string;

,這裏是我如何將它們添加到列表中Form2

Form2 frm = new Form2(); 
frm.Show(); 

Articles = _articles; 
frm.SetData(Articles); 
this.Hide(); 

Form4代碼非常相似,從Form3代碼..只是另一個列表。

這裏是ListArticle類:

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

所以基本上我想添加的元素我Form4在我Form3添加元素的末尾添加。

+0

在'Form3,Form4,Form5 ...'你創建'Form2'的新實例?如果這樣做是錯誤的。您需要有一個Form2實例,並且所有其他表單必須訪問Form2s文章列表。 – Reniuz

+0

@Reniuz我做這樣的事情:'Form2 frm = new Form2(); frm.Show();'。我如何創建一個Form2實例? –

回答

1

在你的問題你提到Form4代碼非常相似,從Form3代碼」

然而,在Form3你犯了一個新的ListArticle:public ListArticle _articles = new ListArticle();如果你做Form4相同,而其他形式的比是正常的列表是由每個窗體覆蓋。每個表單都創建了自己的新列表。

我認爲你想要做的是在你的主程序Program.cs而不是Form2上創建一個公開的Buffer字段。像這樣:

static class Program 
{ 
    public ListArticle Buffer = new ListArticle(); // Add this line 

    static void Main() 
    .... 
} 

這樣你就可以從每一個表格Program.Buffer訪問您的緩衝區。

而且你可以在每個表單如添加新的文章到您的緩衝區:

Program.Buffer.Clothes.Add(...) 
Program.Buffer.Colors.Add(...) 
+0

我在哪裏申報在我的'Program.cs'類似的東西? –

+0

爲什麼我不能直接從'Program.cs'中使用列表,並且必須創建一個單獨的變量'thisArticle;'? –

+0

@ C.Cristi,添加緩衝的聲明中靜態類節目{}的大括號之間的某個地方,在同一水平上的靜態無效的主要()。 – flip

0

這條線......

_Buffer = article; 

...你是以新的清單取代以前的列表。顯然,前一個列表中的所有條目在該過程中都會丟失。您需要添加新的列表中的條目:

if (_Buffer == null) { 
    _Buffer = new ListArticle(); 
} 
_Buffer.Clothes.AddRange(article.Clothes); 
_Buffer.Colors.AddRange(article.Colors); 
+0

它不包含'GetEnumerator'和方法'Add'的定義,像這樣...我將在問題中發佈我的'ListArticle'類。查看更新! –

+0

@ C.Cristi:看我的更新, – Sefe

+0

仍然不工作 –