2014-02-19 23 views
0

我想帶給型1製備的變量(金額和利率)爲表3 我需要把表格1製作成標籤中的變量形式3或得到變量形式1到形式3.是否有任何方式將變量從一種形式傳遞到另一種形式,以及如何?帶來變量從一種形式到另

namespace InvestmentCalc 
{ 
public partial class Form1 : Form 
{ 
    decimal Amount; 
    decimal WeekInterest; 
    decimal TwoWeekInterest; 
    decimal MonthInterest; 
    decimal ThreeMonthInterest; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void nextButton_Click(object sender, EventArgs e) 
    { 
     ParseItems(); 
     Formchange(); 
    } 
     private void ExitButton_Click(object sender, EventArgs e) 
     { 
      this.Close(); 
     } 

     private void ClearButton_Click(object sender, EventArgs e) 
     { 

     } 

    //Methods 

     public void ParseItems() 
     { 
      WeekInterest = decimal.Parse(WeekIntTextBox.Text); 
      TwoWeekInterest = decimal.Parse(tWeekIntTextBox.Text); 
      MonthInterest = decimal.Parse(monthIntTextBox.Text); 
      ThreeMonthInterest = decimal.Parse(threeMonthIntTextBox.Text); 
      Amount = decimal.Parse(DepositTextBox1.Text); 
     } 

     public void Formchange() 
     { 
      Form3 Check = new Form3(); 
      Check.Show(); 
      Hide(); 
     }             
    } 

回答

0

是的,當然,但你必須尋找更高層次的解決方案。首先,實例化第一種形式,然後例如顯示它的模式,當調用返回時,從該表單讀取屬性並將它們傳遞給下一個。

int amount, interest; 
using (Form1 form = new Form1()) 
{ 
    form.ShowDialog(); 
    amount = form.Amount;  // these, of course, have to be public 
    interest = form.Interest; // make the fields private and expose them via properties 
    [...] 
} 

using (Form2 form = new Form2(amount, interest)) 
{ 
    form.ShowDialog(); 
} 

ShowDialog()返回時窗體關閉,所以它可能是這裏最容易的事情。

根據您需要多少個值傳遞,創造一個結構或類到他們移交可能是一個很好的策略。

[編輯:相比較於其他的答案,這將產生一系列的表格。將當前表單傳遞給新構造函數雖然不一定,但更多的是模態對話方法。如果那確實是你所要求的,那麼你只需要知道你可以用一個需要參數的構造函數來編寫一個表單。

0

有沒有什麼辦法可以將變量從一種形式傳遞給另一種形式?由於

當然,最簡單的方法是定義你的變量public。那麼,當你打開你的第二個表單通過你當前Form實例Show方法:

Form3 f3 = new Form3(); 
f3.Show(this); 

然後裏面的Form3OwnerForm1並訪問您的變量像這樣

((Form1)Owner).VariableName; 
0

如果你想移動許多價值爲另一種形式,在form3首先創建構造函數(在這裏例如派出兩個字符串從Form1以form3)

Public Form3(object[] data) :this() 
{ 
string s1 = data[0].Tostring(); 
string s2 = data[1].Tostring(); 
label1.Text = s1; 
label2.Text = s2; 
} 
在Form1

,現在我們可以創建一個可以收到我們的數據form3,stringA將被髮送將form3作爲s1,將stringB作爲s2發送給form3。

private void button_Click(object sender, Eventargs e) 
{ 
stringA = "my value"; 
stringB = "my another value"; 
object[] data = {stringA, stringB}; 
Form3 frm = new Form3(data); 
frm.Showdialog(); 
} 
相關問題