Windows Forms "The name X does not exist in current context"

86 Views Asked by At

firstly this is my first post here so sorry for bad format and yada yada yada. Now, I'm trying to learn C# for my uni classes and I have a problem with some basic windows forms and c# logic so if you could help me out I would really appreciate it! So, I created my form and it has 2 text boxes and a button. Uppon pressing the button, I want the program to create a new class member for a list. (think i got the explanation a bit wrong in the end so I'll link my code here). So basically here we go: Main program :

    namespace AddPersonTest
{
    public static class Program
    {

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            List<Person> Persoane = new List<Person>();
        }
    }
}

Persons class:

namespace AddPersonTest
{
    public class Person
    {
        public int cod;
        public int sex;

        Person (int nCod, int nSex)
        {
            cod = nCod;
            sex = nSex;
        }
    }
}

Button and textboxes code:

namespace AddPersonTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void lblCod_Click(object sender, EventArgs e)
        {

        }

        public void btnAdd_Click(object sender, EventArgs e)
        {
            Persoane.Add(txtCod, txtSex);
        }

        private void txtSex_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtCod_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
1

There are 1 best solutions below

0
On

In case you wanted to have the persons added on click to be static throughout your application, you could do like the below. You have created the list inside the main method which is not the right place to maintain your application state. Use the below class and on buttonclick, just call PersonStore.AddPerson(....);

public static class PersonStore {

    private static List<Person> persons = new List<Person>();

    public static void AddPerson(Person p) {
        persons.Add(p);
    }

    public static List<Person> GetAllPersons() {
        return persons;
    }

}

In case you wanted to have these handled with services you could just do that with the help of service classes and Data Access layer classes which can be written if your requirement is to store in DB.