2017-01-03 47 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

仍然不工作 –