【问题标题】:Windows Forms "The name X does not exist in current context"Windows 窗体“当前上下文中不存在名称 X”
【发布时间】:2020-05-09 17:03:46
【问题描述】:

首先,这是我在这里的第一篇文章,很抱歉格式不好和 yada yada yada。现在,我正在尝试为我的 uni 课程学习 C#,但我遇到了一些基本的 windows 窗体和 c# 逻辑的问题,所以如果你能帮助我,我将不胜感激! 所以,我创建了我的表单,它有 2 个文本框和一个按钮。按下按钮后,我希望程序为列表创建一个新的类成员。 (认为​​我最后的解释有点错误,所以我将在这里链接我的代码)。所以基本上我们开始了: 主程序:

    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>();
        }
    }
}

人物类:

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

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

按钮和文本框代码:

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)
        {

        }
    }
}

【问题讨论】:

  • “名称 X 在当前显示的代码中不存在”

标签: c# windowsformsintegration


【解决方案1】:

如果您想让点击时添加的人员在整个应用程序中保持静态,您可以执行以下操作。您已经在 main 方法中创建了列表,这不是维护应用程序状态的正确位置。使用下面的类和按钮点击,只需调用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;
    }

}

如果您想通过服务处理这些问题,您可以借助服务类和数据访问层类来实现,如果您的要求是存储在 DB 中,可以编写这些类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 2014-04-22
    • 2017-06-17
    相关资源
    最近更新 更多