繁体   English   中英

C# - 如何在我的 winforms 应用程序中从另一个 class 引用我当前的 Form1 实例?

[英]C# - How to reference my current instance of Form1 from another class in my winforms application?

如果这没有意义,请道歉。 WinForms 相当新,这是一个统一评估。 我的主窗体如下所示,我想在另一个 class 中调用该方法。我已将 Form1 重命名为 LoginPage。

public partial class LoginPage : Form
    {
        public LoginPage()
        {
            InitializeComponent();
            Customer.LoadCustomerDB();
        }

        public string PinText
        {
            get { return PINNumTxt.Text; }
            set { PINNumTxt.Text = value; }
        }
    }

我的另一个 class 看起来是为了验证我通过上面的 function 访问的 PinText。

    class BankCard
    {
        // Attributes
        private Customer customer;
        private int pinAttempts = 0;
        private bool cardUnusable = false;

        // Member functions
        public void VerifyPIN()
        {
            LoginPage loginPage = new LoginPage();
            foreach (Customer c in Customer.customers)
            {
                if (c.GetID().ToString() == loginPage.AccountNum())
                {
                    customer = c;
                }
            }

            if (cardUnusable == true)
            {
                MessageBox.Show("This card is currently blocked. Please contact your bank.");
                Environment.Exit(0);
            }
            else if (loginPage.PinText == customer.GetPIN())
            {
                MessageBox.Show("Success!");
            }
            else if (pinAttempts < 2)
            {
                MessageBox.Show("Incorrect PIN attempt " + (pinAttempts + 1) + "/3");
                loginPage.PinText = "";
                pinAttempts += 1;
            }
            else
            {
                MessageBox.Show("3 failed PIN attempts. Please contact your bank.");
                cardUnusable = true;
                Environment.Exit(0);
            }
        }
    }

我的问题是我有以下内容:

LoginPage loginPage = new LoginPage();

这将创建主页的一个新实例,将加载的 CustomerDB 加倍并导致我的 VerifyPin() function 出错。

问题是我需要以某种方式让 LoginPage loginPage = LoginPage 的当前实例吗? 如果是这样,我将如何编码?

谢谢你的帮助

Wyck 的评论让它运行起来没有任何错误。 我必须做:

LoginPage loginPage = Application.OpenForms.OfType<LoginPage>().FirstOrDefault();

谢谢大家

在大多数 winforms 项目中,有一个Program class 具有Application.Run(new Form1()); (或者无论你的主要形式是什么,在你的情况下都是LoginPage )。 Program class 中,您可以创建一个 static 变量public static LoginPage loginPage; 然后在Main function 中:

static void Main()
{
    loginPage = new LoginPage();
    Application.Run(loginPage);
}

然后当你想在你的任何类中引用loginPage时,你可以只使用Program.loginPage

暂无
暂无

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

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