简体   繁体   中英

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. I have a form1 with a number of textboxes. I want the input to be saved in a list that is in a different class. I ahve the code in 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

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)

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.

Make minlista public

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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