[英]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.