简体   繁体   English

Windows窗体使用C#将文本框输入保存到不同类的列表中

[英]Windows form save textbox input to list in different class using C#

C# windows form How to save text from textboxes into list when list is in a different class. C#Windows窗体当列表位于不同的类中时,如何将文本框中的文本保存到列表中。 I have a form1 with a number of textboxes. 我有一个带有多个文本框的form1。 I want the input to be saved in a list that is in a different class. 我希望将输入保存在不同类的列表中。 I ahve the code in form1 我在form1中的代码

public void button1_Click(object sender, EventArgs e)
{
    minLista.add(textBox1.Text);
    Form2 Form1 = new Form2();
    this.Hide();
    Form1.Show();
}

in the other class I have 在另一堂课我有

List <string> minLista = new List<string>();

what am I doing wrong? 我究竟做错了什么?

Assuming minList is a public property in Form2.cs you should do something like 假设minList是Form2.cs中的公共属性,则应执行以下操作

public void button1_Click(object sender, EventArgs e)
    {
        ThirdClass newthirdClass = new ThirdClass();
        newthirdClass.MinLista = new List<string>();
        newthirdClass.MinLista.Add(textBox1.Text);
        Form2 myForm2 = new Form2(newthirdClass);
        this.Hide();
        myForm2 .Show();
    }

Keep in mind that the convention is for properties (like I propose you for minLista) to start with a capital letter (ie MinLista) 请记住,约定是针对属性(例如我为minLista提议的属性),以大写字母(即MinLista)开头

EDIT 编辑

Since you need it to be in a third class I would do this 既然您需要进入三等班,我会这样做

public class ThirdClass
{
  public List<string> MinLista {get; set;}
}

public Form Form2
{
   private List<string> minLista;

   public Form2(List<string> mlist)
   {
      minLista = mlist;
   }

}

This way you inject the object you created (which has the reference to the list you want) to Form2. 这样,您将创建的对象(具有对所需列表的引用)注入到Form2中。

Make minlista public 公开Minlista

public List<string> minLista = new List<string>();

Then use 然后使用

 public void button1_Click(object sender, EventArgs e)
{
    Classname a = new Classname();
    a.minLista.add(textBox1.Text);
    Form2 Form1 = new Form2();
    this.Hide();
    Form1.Show();
}

Where is Classname is the name of the class where you declared minLista . 其中, Classname是您在其中声明minLista的类的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM