简体   繁体   English

其他形式的调用方法C#Winforms

[英]Calling methods in Other forms C# Winforms

I am making a POS system with a C# WinForms application and have a Form1 (main screen) and a Checkout screen (can be thought of as Form2). 我正在使用C#WinForms应用程序制作POS系统,并具有Form1 (主屏幕)和Checkout屏幕(可以认为是Form2)。 There is a method in Form1 called clearSale() . Form1有一个名为clearSale() I am trying to call it through this button event in Form2 : 我试图通过Form2此按钮事件来调用它:

private void btnProccessComplete_Click(object sender, EventArgs e)
{
    MessageBox.Show("Order Successfully Processed for: $" + checkoutTotal.ToString("F2"), "Successful Payment", MessageBoxButtons.OK, MessageBoxIcon.Information);
    readyStock(checkoutItems);
    isCheckoutComplete = true;
    Form1 myObj = new Form1();
    myObj.clearSale();
    this.Close();
}

In result of this event finishing it calls the clearSale() method from Form1 : 完成此事件后,将调用Form1clearSale()方法:

public void clearSale()
{
    itemList.Items.Clear();
    txtUPCScan.Clear();
    orderTotal = 0.00;
    lblTotalPrice.Text = "$0.00";
    picPay.Enabled = false;
    myShoppingCartItems = null;
    myShoppingCartItems = new string[250];
    totalItems = 0;
}

The clearSale() method pretty much just sets all the txtboxes back to an empty state and makes everything look brand new again. clearSale()方法几乎只是将所有clearSale()设置为空状态,并使所有内容再次看起来都是全新的。 My issue is whenever the clearSale() method gets called in Form1 it will work, but when it is called in Form2 (like I'm trying to get it to) nothing changes on my main page. 我的问题是,每当在Form1调用clearSale()方法都可以使用时,但是在Form2调用它(例如我试图将其调用)时,主页上没有任何变化。 Like the method almost wasn't called. 就像几乎没有调用该方法一样。 Everything stays the same and doesn't get cleared. 一切保持不变,不会被清除。 Any help? 有什么帮助吗?

If you're creating a new Form1 object it will not reference the previously created ones. 如果要创建一个新的Form1对象,它将不会引用以前创建的对象。 Pass Form1 by a constructor parameter to Form2 . 通过构造函数将Form1传递给Form2

public class Form2: Form{

    Form1 mainObj;

    public Form2(Form1 _mainObj){
        this.mainObj = _mainObj;
    }

    private void btnProccessComplete_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Order Successfully Processed for: $" + checkoutTotal.ToString("F2"), "Successful Payment", MessageBoxButtons.OK, MessageBoxIcon.Information);
        readyStock(checkoutItems);
        isCheckoutComplete = true;
        this.mainObj.clearSale();
        this.Close();
    }
}

From Form1 you now have to create Form2 with: 现在,您必须在Form1使用以下方法创建Form2

Form2 checkout = new Form2(this);

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

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