簡體   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