[英]Pass List from Form3 to Form1
I have 3 forms: form1(which I want to use my List from form3 in which I create List and Add things to it), form2 ( which contains a button to go back to form1 and a button to go to form3 and get values to the list. 我有3种形式:form1(我想使用来自form3的List,在其中创建List并向其中添加内容),form2(其中包含一个返回form1的按钮和一个进入form3并获取值的按钮名单。
I tried creating the following class: 我尝试创建以下类:
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>();
}
}
and then declare trying Adding things in the List from form3 like this: 然后声明尝试像这样从form3向列表中添加内容:
// This is the Declaration //这是宣言
public ListArticle _articles = new ListArticle();
public ListArticle Articles
{
get
{
return _articles;
}
set
{
_articles = value;
}
}
This is how I add: 这是我添加的方式:
_articles.Clothes.Add("T-shirt " + tshirt_number.ToString());
_articles.Colors.Add(closestColor2(clist, color));
and this is how I am trying to get the values: 这就是我试图获取值的方式:
when I close form3 当我关闭form3时
I do this: 我这样做:
Form2 frm = new Form2();
frm.Show();
Articles = _articles;
this.Hide();
in form2 I do nothing.. 在form2中,我什么也没做。
and in form1 I tried to do it like this: 在form1中,我试图这样做:
//declaration //宣言
public ListArticle Articles;
public ListArticle _articles
{
get
{
return Articles;
}
set
{
Articles = value;
}
}
//and this is how I tried to do it but it returns null everytime. //这是我尝试执行的操作,但是每次都会返回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.");
}
}
If you want to be able to share the articles between all forms you could make the Clothes and Colors collection static: 如果您希望能够在所有形式之间共享文章,则可以将“衣服和颜色”集合设为静态:
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>();
}
}
You can then add articles form one form like this: 然后,您可以像这样的一种形式添加文章:
ListArticle.Clothes.Add("T-shirt " + tshirt_number.ToString());
ListArticle.Colors.Add(closestColor2(clist, color));
...and retrieve articles from another form like this: ...并从另一种形式检索文章:
private void button3_Click(object sender, EventArgs e)
{
try
{
foreach (string c in ListArticle.Clothes)
{
MessageBox.Show(c);
}
}
catch
{
MessageBox.Show("Articles is null.");
}
}
Using this approach you don't have to create any additional "article" properties in either of the forms. 使用这种方法,您不必在任何一种形式中都创建任何其他“文章”属性。 You just access the same static collections from all forms. 您只需从所有表单访问相同的静态集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.