2017-06-01 31 views
0

我正在用C#WinForms應用程序製作一個POS系統,並有一個Form1(主屏幕)和一個Checkout屏幕(可以認爲是Form2)。在Form1中有一種叫做clearSale()的方法。我想在Form2調用它通過這個按鈕事件:其他形式的調用方法C#Winforms

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

在這種情況下的結果整理它調用從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; 
} 

clearSale()方法非常簡單,只是將所有的txtboxes恢復到空白狀態,並使所有內容再次煥然一新。我的問題是,只要clearSale()方法在Form1中被調用,它就可以工作,但是當它在Form2中被調用時(就像我想要的那樣),我的主頁上沒有任何變化。就像這個方法幾乎沒有被調用。一切都保持不變,不會被清除。任何幫助?

+0

你實例化一個新的'Form1',而不是使用正在顯示 – FortyTwo

+0

谷歌你的問題標題Form1'的'實例。你會發現數百個與答案相同的問題。 – Crowcoder

回答

1

如果您要創建新的Form1對象,它將不會引用先前創建的對象。 通過構造函數參數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(); 
    } 
} 

Form1你現在必須創建Form2有:

Form2 checkout = new Form2(this);